php - 不能使用 null 作为 PHP-8 中参数的默认值
问题描述
在 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) {}
}
那么这也是一个错误还是预期的行为?
解决方案
...因为提升的参数意味着属性声明,所以必须显式声明可空性,并且不能从空默认值推断:
class Test { // Error: Using null default on non-nullable property public function __construct(public Type $prop = null) {} // Correct: Make the type explicitly nullable instead public function __construct(public ?Type $prop = null) {} }
推荐阅读
- r - 使用两个向量作为指示符折叠行
- python - 在python中访问另一个类的方法
- django - 在 Python 中重构 try 和 except 代码块
- css - angularjs中的警报对话框导致页面滚动到顶部
- mongodb - 如何使用 Golang 和 MongoDriver 解决“命令查找需要身份验证”
- xslt-1.0 - 将模板应用于其兄弟元素具有特定属性值的元素
- javascript - Angular7,获取 ElementRef
- r - 收集高程数据 - 从 geotiff 文件中提取地理位置
- spring-boot - 为什么在交换访问令牌的授权码时收到无效的令牌响应?(弹簧靴,oauth2,天蓝色)
- asp.net-web-api - 使用特定列表以角度检索数据