为什么在引入属性类型提示时突然出现“初始化前不能访问类型化属性”错误?

问题描述 投票:4回答:1

我已经更新了类定义,以利用新引入的属性类型提示,如下所示:

class Foo {

    private int $id;
    private ?string $val;
    private DateTimeInterface $createdAt;
    private ?DateTimeInterface $updatedAt;

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


    public function getId(): int { return $this->id; }
    public function getVal(): ?string { return $this->val; }
    public function getCreatedAt(): ?DateTimeInterface { return $this->createdAt; }
    public function getUpdatedAt(): ?DateTimeInterface { return $this->updatedAt; }

    public function setVal(?string $val) { $this->val = $val; }
    public function setCreatedAt(DateTimeInterface $date) { $this->createdAt = $date; }
    public function setUpdatedAt(DateTimeInterface $date) { $this->updatedAt = $date; }
}

但是在尝试将我的实体保存在Doctrine上时,出现错误消息:

初始化前不得访问Typed属性

[不仅发生在$id$createdAt,而且发生在$value$updatedAt,它们都是可为空的属性。

php doctrine-orm php-7 type-hinting php-7.4
1个回答
7
投票

由于PHP 7.4引入了属性的类型提示,因此为所有属性提供有效值特别重要,以便所有属性都具有与其声明的类型相匹配的值。

一个从未赋值的变量没有null值,但它处于undefined状态,它永远不会与任何声明的类型匹配undefined !== null

对于上面的代码,如果您这样做:

$f = new Foo(1);
$f->getVal();

您会得到:

致命错误:未被捕获的错误:键入的属性Foo :: $ val初始化前不能访问

由于$val在访问时既不是string也不是null。>

解决此问题的方法是将值分配给与声明的类型匹配的所有属性。您可以将其作为属性的默认值,也可以在构造期间执行此操作,具体取决于您的偏好和属性的类型。

例如,对于以上所述,您可以这样做:

class Foo {

    private int $id;
    private ?string $val = null; // <-- declaring default null value for the property
    private DateTimeInterface $createdAt;
    private ?DateTimeInterface $updatedAt;

    public function __construct(int $id) {
        // and on the constructor we set the default values for all the other 
        // properties, so now the instance is on a valid state
        $this->id = $id;
        $this->createdAt = new DateTimeImmutable();
        $this->updatedAt = new DateTimeImmutable();
    }

现在所有属性都将具有valid

值,并且实例将处于有效状态。

当您依靠数据库中的值作为实体值时,这种情况尤其常见。例如。自动生成的ID,或创建和/或更新的值;这通常是数据库问题。

对于自动生成的ID,the recommended way forward将类型声明更改为?int $id = null。对于其余所有内容,只需为属性的类型选择一个适当的值。

© www.soinside.com 2019 - 2024. All rights reserved.