我想创建一个继承(扩展)另一个 PHP 类的类,该类带有一个 protected 常量,我想在扩展类中覆盖该常量。
我创建了一个父类(例如A)和一个继承类(例如B)。 class A
有一个protected const
(名为 CST)定义。 class B
也覆盖这个常量。
当调用从 A 继承的方法类 B 时,显示 self::CST
,打印的值是来自 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 的代码可重用性?
最佳答案
Dharman 建议使用 static::CST
而不是 self::CST
。
这就是我的问题的解决方案。
关于PHP 静态属性和 const 覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55782142/