A
A
Alexander2020-04-26 09:21:30
PHP
Alexander, 2020-04-26 09:21:30

The property ... is not readable because it is typed "string". But why?

I used a new php7.4 feature - strict typing of variables, but gives an error

The property "App\Entity\Conference::$slug" is not readable because it is typed "string". You should either initialize it or make it nullable using "?string" instead.

Wherein
private ?string $slug;
// ...
public function getSlug(): ?string
    {
        return $this->slug;
    }

    public function setSlug(string $slug): self
    {
        $this->slug = $slug;

        return $this;
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2020-04-26
@AleksandrB

Found. For those who run into this, the reason is that the language designers consider it bad practice to default null to an empty property that they won't support.
private ?string $slug = null;

R
Rsa97, 2020-04-26
@Rsa97

If a typed property does not have a default value, no implicit null default value is implied (even if the property is nullable). Instead, the property is considered to be uninitialized. Reads from uninitialized properties will generate a TypeError
https://wiki.php.net/rfc/typed_properties_v2#unini...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question