不能将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的默认值

通过使字符串可以为null

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

那么,这是一个错误还是有意为之?

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

。。。由于提升的参数意味着属性声明,因此必须显式声明为null的能力,而不是从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) {}
}

这不是bug!

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

以上代码是的简短语法

class Foo {
private string $string = null;
public function __construct(string $string) {
$this->string  = $string;
}
}

这会产生致命错误

致命错误:字符串类型的属性的默认值可能不是无效的

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

最新更新