fsi-open / files

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Typed property must not be accessed before initialization

pawloaka opened this issue · comments

Hello again,

My User entity looks like this:

class User
{
    private int $id;

    private ?WebFile $cover;

    private string $coverPath;

    public function __construct(?WebFile $cover)
    {
        $this->cover = $cover;
    }

    public function setCover(?WebFile $cover): void
    {
        $this->cover = $cover;
    }

    public function getCover(): ?WebFile
    {
        return $this->cover;
    }
}

And controller which is suitable for creating user:

...
use FSi\Component\Files\Upload\FileFactory;
use FSi\Component\Files\UploadedWebFile;
...

class StartController extends AbstractController
{
    private FileFactory $fileFactory;

    public function __construct(FileFactory $fileFactory)
    {
        $this->fileFactory = $fileFactory;
    }
    public function __invoke(ServerRequestInterface $request): Response
    {
        /** @var UploadedWebFile $file */
        $file = ...
        $book = new User($file);
        $this->em->persist($user);
        $this->em->flush();
		
        return $this->json([]);
    }
}

After going to the url of this controller, I get the following error:

Typed property App\User::$coverPath must not be accessed before initialization

What could be wrong?
Thanks in advance!

The class properties are accessed via reflection and you do not have a default value for yours. This will cause an exception in PHP 7.4, so you need to make both cover and coverPath nullable and with a default null, like so.

    private ?WebFile $cover = null;
    private ?string $coverPath = null;

Thanks 👍