With the introduction of property type hints in PHP 7.4, it is crucial to assign valid values to all properties to ensure their declared types are respected. An undefined property, with no assigned value, fails to match any declared type and triggers the error message: "Typed property must not be accessed before initialization".
For instance, consider the code below:
class Foo { private string $val; public function __construct(int $id) { $this->id = $id; } public function getVal(): string { return $this->val; } }
Accessing $val after constructing Foo would result in the error, as its type is not yet defined (undefined !== null).
To resolve this, assign values to all properties during construction or set default values for them:
class Foo { private string $val = null; // default null value public function __construct(int $id) { $this->id = $id; } }
Now, all properties have valid values, eliminating the error.
This issue can also arise when relying on database values for entity properties, such as auto-generated IDs or timestamps. For auto-generated IDs, declare them as nullable:
private ?int $id = null;
For all others, choose appropriate default values that match their types.
The above is the detailed content of How to Fix 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!