Home > Article > Backend Development > Why Am I Getting the \"Typed Property Must Not Be Accessed Before Initialization\" Error in PHP?
When introducing property type hints in your PHP classes, you may encounter an error stating, "Typed property must not be accessed before initialization." This error occurs when accessing a property before it has been initialized with a valid value matching its declared type.
According to PHP 7.4's type-hinting for properties, all properties must have values matching their declared types. An unassigned property is in an undefined state and will not match any declared type, even null.
Consider the following code:
class Foo { private int $id; private ?string $val; private DateTimeInterface $createdAt; private ?DateTimeInterface $updatedAt; // Getters and setters omitted for brevity... } $f = new Foo(1); $f->getVal(); // Error: Typed property Foo::$val must not be accessed before initialization
In this example, accessing the $val property without assigning it a string or null value first throws an error.
Default Values:
You can assign default values to properties during declaration:
class Foo { private ?string $val = null; // Default null value for optional property }
Constructor Initialization:
Initialize properties in the constructor:
class Foo { public function __construct(int $id) { // Assign values to all properties $this->id = $id; $this->createdAt = new DateTimeImmutable(); $this->updatedAt = new DateTimeImmutable(); } }
Nullable Types:
For optional properties, declare them as nullable:
private ?int $id;
DB Generated Values (Auto-Generated IDs):
Use nullable types for properties initialized by the database:
private ?int $id = null;
The above is the detailed content of Why Am I Getting the \"Typed Property Must Not Be Accessed Before Initialization\" Error in PHP?. For more information, please follow other related articles on the PHP Chinese website!