Home > Backend Development > PHP Tutorial > Why Do I Get a \'Typed Property Must Not Be Accessed Before Initialization\' Error in PHP?

Why Do I Get a \'Typed Property Must Not Be Accessed Before Initialization\' Error in PHP?

Susan Sarandon
Release: 2024-11-16 20:48:03
Original
874 people have browsed it

Why Do I Get a

Understanding "Typed Property Must Not Be Accessed Before Initialization" Error in Properties with Type Hints

PHP 7.4 introduced type-hinting for properties, necessitating proper initialization of all properties. When a property lacks an assigned value, it remains in an undefined state that could conflict with its declared type.

For instance, if we declare:

class Foo {
    private int $id;
    private ?string $val;
    private DateTimeInterface $createdAt;
    private ?DateTimeInterface $updatedAt;
}
Copy after login

Accessing $val without prior initialization would result in the error: "Typed property Foo::$val must not be accessed before initialization." This is because $val is neither a string nor null when accessed.

To resolve this, assign valid values to all properties, either as default values or during construction. For the above example, we could use:

class Foo {
    private int $id;
    private ?string $val = null;
    private Collection $collection;
    private DateTimeInterface $createdAt;
    private ?DateTimeInterface $updatedAt;

    public function __construct(int $id) {
        // Setting default values for other properties
        $this->id = $id;
        $this->createdAt = new DateTimeImmutable();
        $this->updatedAt = new DateTimeImmutable();

        $this->collection = new ArrayCollection();
    }
}
Copy after login

By doing so, all properties have valid values and the instance is in a valid state.

This error can commonly occur when relying on database-generated values such as IDs or timestamps. For auto-generated IDs, it's advisable to change the type declaration to private ?int $id = null. For other values, choose suitable defaults that match the property's type.

The above is the detailed content of Why Do I Get a '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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template