Cat*_*ish 7 php types type-hinting
为什么我会收到此错误
未捕获的类型错误:类型化属性 $description 必须是字符串,使用 null
当我尝试分配null给类型属性时?像这样:
new Foo(null);
Run Code Online (Sandbox Code Playgroud)
class Foo
{
private string $description;
public function __construct($description)
{
$this->description = $description; // <-- Error on this line
}
}
Run Code Online (Sandbox Code Playgroud)
yiv*_*ivi 13
如果您希望声明一个属性能够同时保存特定类型 或,则可以在类型声明之前null添加。?
使用你的例子:
class Foo
{
private ?string $description;
public function __construct(?string $description)
{
$this->description = $description;
}
}
Run Code Online (Sandbox Code Playgroud)