考虑下面的例子。 A类有private const SOMETHING
,但是 b 类有protected const SOMETHING
.
class a {
private const SOMETHING = 'This is a!';
public static function outputSomething() {
return static::SOMETHING ?? self::SOMETHING;
}
}
class b extends a {
protected const SOMETHING = 'This is b!';
}
echo (new b())::outputSomething();
Output:
This is b!
但现在如果我注释掉定义SOMETHING
在b类中,抛出错误:
class a {
private const SOMETHING = 'This is a!';
public static function outputSomething() {
return static::SOMETHING ?? self::SOMETHING;
}
}
class b extends a {
//protected const SOMETHING = 'This is b!';
}
echo (new b())::outputSomething();
Output:
Fatal error: Uncaught Error: Cannot access private const b::SOMETHING in {file}.php:7
但是,改变可见性private const SOMETHING
to protected const SOMETHING
在a类中修复了这个问题。
class a {
protected const SOMETHING = 'This is a!';
public static function outputSomething() {
return static::SOMETHING ?? self::SOMETHING;
}
}
class b extends a {
//protected const SOMETHING = 'This is b!';
}
echo (new b())::outputSomething();
现在输出符合预期:
This is a!
我不明白为什么 php 在应用空合并运算符之前评估 b::SOMETHING ,根据文档 http://php.net/manual/en/migration70.new-features.php:
添加了空合并运算符 (??) 作为语法糖
对于需要结合使用三元的常见情况
伊塞特()。如果第一个操作数存在且不为 NULL,则返回;
否则返回第二个操作数。
由于未设置 b::SOMETHING,为什么第一个示例不起作用并且基类中的常量需要一致的可见性?