首页 > 解决方案 > 不能使用 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) {}
}

那么这也是一个错误还是预期的行为?

标签: phpclassnullablephp-8property-promotion

解决方案


请参阅构造函数属性提升的 RFC

...因为提升的参数意味着属性声明,所以必须显式声明可空性,并且不能从空默认值推断:

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) {}
}

推荐阅读