PHP-8 中不能使用 null 作为参数的默认值

5 php nullable class php-8 property-promotion

在 php-8 及更早版本中,以下代码有效

class Foo {
    public function __construct(string $string = null) {}
}
Run Code Online (Sandbox Code Playgroud)

但是在php-8中,随着属性提升,它会抛出错误

class Foo {
    public function __construct(private string $string = null) {}
}
Run Code Online (Sandbox Code Playgroud)

致命错误:不能使用 null 作为字符串类型参数 $string 的默认值

不过,使字符串可为空是可行的

class Foo {
    public function __construct(private ?string $string = null) {}
}
Run Code Online (Sandbox Code Playgroud)

那么这也是一个错误还是有意的行为?

Phi*_*hil 13

请参阅构造函数属性促销的 RFC

...因为提升的参数意味着属性声明,所以必须显式声明可为空性,并且不能从 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) {}
}
Run Code Online (Sandbox Code Playgroud)