微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么PHP的null合并运算符(??)不能处理具有不同可见性的类常量?

考虑下面的例子.类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合并格式.

这实际上归结为私人可见性的不当使用.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐