Home >Backend Development >PHP Tutorial >Why Does PHP Throw \'Typed Property Must Not Be Accessed Before Initialization\'?
PHP 7.4 introduced type-hinting for properties, emphasizing the need to provide valid values for all properties. However, accessing properties without assigning them can lead to an error, as undefined properties do not match declared types.
Consider the following code:
class Foo { private int $id; private ?string $val; private DateTimeInterface $createdAt; private ?DateTimeInterface $updatedAt; public function __construct(int $id) { $this->id = $id; } }
Trying to access $val before assigning it would result in:
Fatal error: Typed property Foo::$val must not be accessed before initialization
To resolve this, assign values matching declared types either as default values or during construction. For example:
class Foo { private int $id; private ?string $val = null; private ?DateTimeInterface $updatedAt; public function __construct(int $id) { $this->id = $id; $this->createdAt = new DateTimeImmutable(); $this->updatedAt = new DateTimeImmutable(); } }
This ensures all properties have valid values, eliminating the error.
When dealing with auto-generated values like IDs, declaring the property as private ?int $id = null is recommended. For other properties with no specific assignment, choose appropriate default values based on their types.
The above is the detailed content of Why Does PHP Throw \'Typed Property Must Not Be Accessed Before Initialization\'?. For more information, please follow other related articles on the PHP Chinese website!