PHP静态属性和const覆盖

PHP static properties and const overriding

本问题已经有最佳答案,请猛点这里访问。

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

我创建了一个父类(示例中为A)和一个继承类(示例中为B)。 class A定义了protected const(命名为CST)。 class B也会覆盖此const。

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class A
{
        protected static $var = 1;
        protected const CST = 1;

        public static function printVar()
        {
                print self::$var ."
"
;
        }

        public static function printCST()
        {
                print self::CST ."
"
;
        }

}

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的代码可重用性?


Dharman建议使用static::CST而不是self::CST

这是我的问题的解决方案。