我可以声明类型化的 属性 以便它也接受空值吗?

Can I declare a typed property so that it accepts a null value as well?

为什么我会收到此错误

Uncaught TypeError: Typed property $description must be string, null used

当我尝试将 null 分配给键入的 属性 时?像这样:

new Foo(null);
class Foo
{
  private string $description;

  public function __construct($description)
  {
    $this->description = $description; // <-- Error on this line
  }
}

PHP 支持 nullable types since PHP 7.1

如果您想声明一个 属性 以能够同时包含特定类型或 null,您可以在类型声明前添加 ?

使用你的例子:

class Foo
{
  private ?string $description;

  public function __construct(?string $description)
  {
    $this->description = $description;
  }
}