Home > Backend Development > PHP Tutorial > How to Fix the \'Typed Property Must Not Be Accessed Before Initialization\' Error in PHP?

How to Fix the \'Typed Property Must Not Be Accessed Before Initialization\' Error in PHP?

DDD
Release: 2024-11-20 04:52:02
Original
367 people have browsed it

How to Fix the

Understanding the "Typed Property Must Not Be Accessed Before Initialization" Error

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; }
}
Copy after login

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;
    }
}
Copy after login

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;
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template