如何从子类中覆盖静态父级属性

时间:2016-09-07 07:07:32

标签: php oop

简化的演示代码:

<?php

class ParentClass {
    protected static $property = 1;

    public static function getProperty() {
        return self::$property;
    }
}

class ChildClass extends ParentClass {
    protected static $property = 2;
}

echo ChildClass::getProperty(); // Returns 1. I expected it to return 2.

?>

在上面的代码中,我希望在$property内覆盖ChildClass的值,因此ChildClass::getProperty()返回2,但这不是结果。

我希望我能清楚自己想要实现的目标。解决这个问题的正确方法是什么,为什么上面的代码没有按预期运行?

1 个答案:

答案 0 :(得分:0)

您需要使用static代替self

<?php

class ParentClass {
    protected static $property = 1;

    public static function getProperty() {
        return static::$property;
    }
}

class ChildClass extends ParentClass {
    protected static $property = 2;
}

echo ChildClass::getProperty(); // Returns 2

self指的是您使用关键字的类。