【问题标题】:Cannot use null as default value for parameter in PHP-8不能使用 null 作为 PHP-8 中参数的默认值
【发布时间】:2021-02-05 01:45:45
【问题描述】:

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

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

【问题讨论】:

  • 为什么你会认为这是一个错误?错误消息很清楚这是故意的
  • @Phil 因为默认值 null 不需要 AFAIK 可空值,不是吗?删除private 时不会抛出错误,因此存在疑问。

标签: php class nullable php-8 property-promotion


【解决方案1】:

这不是错误!

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

上面的代码是一个简写语法

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

这会产生致命错误

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

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

【讨论】:

    【解决方案2】:

    RFC for Constructor Property Promotion

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-01
      • 2016-11-24
      • 2013-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-27
      • 2010-09-21
      相关资源
      最近更新 更多