Home  >  Article  >  Backend Development  >  Why Do I Get a \"Typed Property Not Initialized\" Error with PHP 7.4 Property Type Hints?

Why Do I Get a \"Typed Property Not Initialized\" Error with PHP 7.4 Property Type Hints?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-17 15:56:02555browse

Why Do I Get a

Why You May Encounter a "Typed Property Not Initialized" Error with Property Type Hints

When utilizing the new property type hints in PHP 7.4, it's crucial to provide valid values for all properties. Unlike null values, undefined properties don't match any declared type.

For instance, with the following class:

class Foo {
    private int $id;
    private ?string $val;
    private DateTimeInterface $createdAt;
    private ?DateTimeInterface $updatedAt;

    public function __construct(int $id) {
        $this->id = $id;
    }
}

Accessing $val directly will result in a "Typed property not initialized" error since it has no valid value (neither string nor null).

To resolve this, ensure that all properties have appropriate values upon initialization. Default values or setting values during construction are two options:

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

    public function __construct(int $id) {
        $this->id = $id;
        $this->createdAt = new DateTimeImmutable();
        $this->updatedAt = new DateTimeImmutable();
    }
}

For auto-generated IDs, the recommended approach is to define the property as nullable:

private ?int $id = null;

Remember, undefined properties don't have null values, and their values must always match their declared types. By providing initial values or default values, you can prevent this initialization error and ensure a valid instance state.

The above is the detailed content of Why Do I Get a \"Typed Property Not Initialized\" Error with PHP 7.4 Property Type Hints?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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