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

Cannot use null as default value for parameter in PHP-8

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

class Foo {
    public function __construct(string $string = null) {}
}

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

class Foo {
    public function __construct(private string $string = null) {}
}

Fatal error: Cannot use null as default value for parameter $string of type string

使字符串可以为 null 是可行的

class Foo {
    public function __construct(private ?string $string = null) {}
}

这也是错误还是有意为之?

RFC for Constructor Property Promotion

...because promoted parameters imply a property declaration, nullability must be explicitly declared, and is not inferred from a null default value:

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

这不是错误!

class Foo {
    public function __construct(private string $string = null) {}
}

以上代码是

的简写语法
class Foo {
    private string $string = null;
    public function __construct(string $string) {
        $this->string  = $string;
    }
}

这会产生致命错误

Fatal error: Default value for property of type string may not be null.

因此您无法将不可为空的类型 属性 初始化为 NULL