编程

"Typed property must not be accessed before initialization" - 引入类型提示遇到的错误

104 2024-04-16 16:56:00

在 PHP 中,当属性的定义使用了类型提示,而在显式赋值前访问该属性时,会碰到 "Typed property must not be accessed before initialization" 错误。

通过为该属性提供默认值,或者在类的构造函数中初始化该属性,可以解决这一问题。

以下是如何通过为属性提供默认值修复这一错误:

<?php

// Define a new class called MyClass
class MyClass
{
  /**
   * @var int
   */
  // Define a private property called "myProperty" and initialize it to 0
  private int $myProperty = 0;

  // Define a public method called "getMyProperty" that returns the value of "myProperty"
  public function getMyProperty(): int
  {
    return $this->myProperty;
  }

  // Define a public method called "setMyProperty" that takes an integer value and sets "myProperty" to that value
  public function setMyProperty(int $value): void
  {
    $this->myProperty = $value;
  }
}

// Create a new instance of MyClass called "myObject"
$myObject = new MyClass();

// Call the "getMyProperty" method on "myObject" and store the result in a variable called "value"
$value = $myObject->getMyProperty();

// Output the value of "value"
echo "The initial value of myProperty is: " . $value . "\n";

// Call the "setMyProperty" method on "myObject" and set "myProperty" to 42
$myObject->setMyProperty(42);

// Call the "getMyProperty" method on "myObject" again and store the result in "value"
$value = $myObject->getMyProperty();

// Output the new value of "value"
echo "The new value of myProperty is: " . $value . "\n";

此外,你可以在构造函数中初始化

<?php

class MyClass
{
  /**
   * @var int
   */
  private int $myProperty;

  public function __construct()
  {
    $this->myProperty = 0;
  }

  public function getMyProperty(): int
  {
    return $this->myProperty;
  }

  public function setMyProperty(int $value): void
  {
    $this->myProperty = $value;
  }
}

// Example usage
$obj = new MyClass();
echo $obj->getMyProperty() . PHP_EOL; // Output: 0
$obj->setMyProperty(42);
echo $obj->getMyProperty(); // Output: 42

这种方法,当类被初始化后,解析器可以使用默认值中初始化该属性或者在构造函数中设置属性值,这样就能解决该错误。

 

 

PHP