如何在 super class 的静态方法中检索 subclass 的静态 属性
How to retrieve a static property of the subclass in a static method in the super class
我遇到类似下面代码的情况:
class ParentClass
{
public static $property = 'parentValue';
public static function doSomethingWithProperty() {
echo 'Method From Parent Class:' . self::$property . "\n";
}
}
class ChildClass extends ParentClass
{
public static $property = 'childValue';
}
echo "Directly: " . ChildClass::$property . "\n";
ChildClass::doSomethingWithProperty();
运行 我从 cli 得到输出:
Directly: childValue
Method From Parent Class: parentValue
有没有办法从父 class 中定义的静态方法中检索子 class 中定义的静态 属性?
使用 self
关键字总是引用相同的 class。
要允许覆盖静态 property/method,您必须使用 static
关键字。您的方法应如下所示
public static function doSomethingWithProperty()
{
echo 'Method From Parent Class:' . static::$property . "\n";
}
我遇到类似下面代码的情况:
class ParentClass
{
public static $property = 'parentValue';
public static function doSomethingWithProperty() {
echo 'Method From Parent Class:' . self::$property . "\n";
}
}
class ChildClass extends ParentClass
{
public static $property = 'childValue';
}
echo "Directly: " . ChildClass::$property . "\n";
ChildClass::doSomethingWithProperty();
运行 我从 cli 得到输出:
Directly: childValue
Method From Parent Class: parentValue
有没有办法从父 class 中定义的静态方法中检索子 class 中定义的静态 属性?
使用 self
关键字总是引用相同的 class。
要允许覆盖静态 property/method,您必须使用 static
关键字。您的方法应如下所示
public static function doSomethingWithProperty()
{
echo 'Method From Parent Class:' . static::$property . "\n";
}