【问题标题】:How to override a static parent's property from within child class [duplicate]如何从子类中覆盖静态父级的属性[重复]
【发布时间】:2016-09-07 07:07:31
【问题描述】:

简化的演示代码:

<?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,但这不是结果。

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

【问题讨论】:

  • 哦!我环顾四周,但没有找到这个问题。谢谢,这正是我要找的。​​span>

标签: php oop


【解决方案1】:

您需要使用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 指的是您在其中使用关键字的类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-20
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多