考虑下面的例子.类a具有私有const SOMETHING,但类b具有保护的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();
输出:
This is b!
但是现在如果我在类b中注释掉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();
输出:
Fatal error: Uncaught Error: Cannot access private const b::SOMETHING in {file}.php:7
但是,在类a中将可见性从私有const SOMETHING更改为受保护的const SOMETHING可以解决此问题.
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在应用null合并运算符之前评估b :: SOMETHING,根据the documentation:
The null coalescing operator (??) has been added as syntactic sugar
for the common case of needing to use a ternary in conjunction with
isset(). It returns its first operand if it exists and is not NULL;
otherwise it returns its second operand.
由于未设置b :: SOMETHING,为什么第一个示例不起作用,并且基类中的常量需要一致的可见性?
解决方法:
Since b::SOMETHING is not set, why doesn’t the first example work and a consistent visibility is required for the constant in the base class?
B :: SOMETHING已设置.这是因为B扩展了A并且你已经将SOMETHING定义为A的常量.问题不在于它没有设置,问题是你没有授予B访问权限,所以它实际上不适合进入null合并格式.
这实际上归结为私人可见性的不当使用.