如何在超类的静态方法中检索子类的静态属性

问题描述 投票:0回答:1

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

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

是否有一种方法可以从父类中定义的静态方法中检索子类中定义的静态属性?

php oop static php-7 static-methods
1个回答
2
投票

使用self关键字始终引用相同的类。

要允许覆盖静态属性/方法,您必须使用static关键字。您的方法应如下所示

public static function doSomethingWithProperty()
{
    echo 'Method From Parent Class:' . static::$property . "\n";
}
© www.soinside.com 2019 - 2024. All rights reserved.