【发布时间】:2021-02-05 01:45:45
【问题描述】:
在 php-8 和更早的版本中,以下代码有效
class Foo {
public function __construct(string $string = null) {}
}
但是在php-8中,随着属性提升,它会抛出一个错误
class Foo {
public function __construct(private string $string = null) {}
}
致命错误:不能使用 null 作为字符串类型的参数 $string 的默认值
虽然使字符串可以为空
class Foo {
public function __construct(private ?string $string = null) {}
}
那么这也是一个错误还是预期的行为?
【问题讨论】:
-
为什么你会认为这是一个错误?错误消息很清楚这是故意的
-
@Phil 因为默认值 null 不需要 AFAIK 可空值,不是吗?删除
private时不会抛出错误,因此存在疑问。
标签: php class nullable php-8 property-promotion