PHP 静态属性和常量覆盖



我想创建一个类,继承(扩展(另一个具有受保护的 const 的 PHP 类,我想在我的扩展类中覆盖它。

我创建了一个父类(示例为 A(和一个继承类(示例为 B(。 class A定义了一个名为 CST 的protected constclass B也会覆盖此常量。

当调用从 A 继承的显示self::CST的方法类 B 时,打印的值是 A 中的 CST 值,而不是在 B 中重写的 const CST。

我对名为 $var 的静态属性观察到相同的行为。

方法中使用的self似乎始终引用定义类(在我的示例中为 A(,而不是用于调用静态方法的类。

class A
{
        protected static $var = 1;
        protected const CST = 1;
        public static function printVar()
        {
                print self::$var . "n";
        }
        public static function printCST()
        {
                print self::CST . "n";
        }
}
class B extends A
{
        protected static $var = 2;
        protected const CST =2;
}
A::printVar();
A::printCST();
B::printVar();
B::printCST();

有没有办法允许我的静态方法printCST()在使用B::printCST()调用时显示 2,而无需在 class B 中重写该方法,并提高 OOP 的代码可重用性?

达曼建议使用static::CST而不是self::CST

这是我问题的解决方案。

最新更新