php-8

Typed property must not be accessed before initialization with ArrayCollection


In project of Symfony 6.2 and PHP 8.1 Issue with initialisation of ArrayCollection

I done this into my entity :

#[OneToMany(targetEntity: CarItem::class, mappedBy: 'car')]
private ?Collection $items;

And my construct function of this entity :

public function __construct()
{
    dump('test');
    $this->items = new ArrayCollection();
}

But when I need to access item like this :

public function getItems(): Collection
{
    return $this->items;
}

It tell me that :

Typed property App\Entity\Module\Car::$items must not be accessed before initialization

I understand that I need to initialize my items variable before access this but I do that into my __construct method before.

Why PHP tell me that ?

All web search tell about simple function or examples with arrayCollection do like me...

What can I do for access items in a Car object exist into database ?


Solution

  • Hello fix your code this way :

    #[OneToMany(targetEntity: CarItem::class, mappedBy: 'car')]
    private ?Collection $items = null;
    

    And

    public function getItems(): ?Collection
    {
        return $this->items;
    }
    

    If you do not want to do that you will have to remove the ? from type hinting.

    Like this :

    #[OneToMany(targetEntity: CarItem::class, mappedBy: 'car')]
    private Collection $items;
    

    By the way, for any other reader, this problem is not related to symfony, its only php type hinting logic from the author project.