【发布时间】:2020-07-11 01:04:05
【问题描述】:
为什么会出现这个错误
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
}
}
【问题讨论】:
-
您将其定义为字符串。如果你不向构造函数传递任何东西,那么它将失败。
-
@FunkFortyNiner 没有完全不同的问题。我想让它成为一个字符串,但也允许为空。在 Java 中,您可以为 String 类型传入 null。
-
@Catfish 好吧。
-
看起来 PHP 通过
?提供了可选类型。private ?string $description允许我传入一个字符串或 null。 php.net/manual/en/migration71.new-features.php
标签: php types type-hinting