首页 > 解决方案 > 如何在超类的静态方法中检索子类的静态属性

问题描述

我的情况类似于以下代码:

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

有没有办法从父类中定义的静态方法中检索子类中定义的静态属性?

标签: phpoopstaticphp-7static-methods

解决方案


使用self关键字总是引用同一个类。

要允许覆盖静态属性/方法,您必须使用static关键字。你的方法应该是这样的

public static function doSomethingWithProperty()
{
    echo 'Method From Parent Class:' . static::$property . "\n";
}

推荐阅读