【问题标题】:PHP Child class self:: targets to parentPHP 子类 self:: 目标为父
【发布时间】:2014-10-14 21:34:02
【问题描述】:

我有父类:

class Parent {

    public static $registered = array();

    public static function register($name){
        self::$registered[] = $name;
    }

}

然后我有了扩展父类的子类。

class Child extends Parent {

}

然后我打电话

Child::register("foo");

我愿意

var_dump( Child::$registered );

但它是空的。 (项目已添加到父数组中,我希望将其添加到子数组中)

是否有可能父函数的 self:: 也会被子类“占用”?

(我希望它是静态的,我不想初始化对象)

http://codepad.org/q9ujGiyM

【问题讨论】:

  • 您的孩子是否也有public static $registered = array();... 如果有,您为什么要覆盖父母的同名公共财产?这似乎毫无意义。但是使用static 而不是self 来引用孩子而不是父母
  • 您使用的是什么 PHP 版本?你发布的内容在 PHP 5.5 中对我有用

标签: php oop inheritance static


【解决方案1】:

您发布的内容从 PHP 5.0.5 开始。

您可以在 3v4l 上验证,对于这些版本,它可以正确输出

array(1) {
  [0]=>
  string(3) "foo"
}

所以最好的答案是:升级你的 PHP。

【讨论】:

    【解决方案2】:

    试试static::$registered[] = $name 而不是self::$registered[] = $name。

    【讨论】:

    • 对我来说也一样,所以它仍然以父级为目标。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    • 2010-10-21
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    相关资源
    最近更新 更多