Home > Backend Development > PHP Tutorial > Why Does PHP Throw \'Typed Property Must Not Be Accessed Before Initialization\'?

Why Does PHP Throw \'Typed Property Must Not Be Accessed Before Initialization\'?

Barbara Streisand
Release: 2024-11-17 07:05:03
Original
305 people have browsed it

Why Does PHP Throw

Why the "Typed Property Must Not Be Accessed Before Initialization" Error Arises with Property Type Hints

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

Trying to access $val before assigning it would result in:

Fatal error: Typed property Foo::$val must not be accessed before initialization
Copy after login

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template