【问题标题】:Modifying parent public variable in child class in PHP在 PHP 中修改子类中的父公共变量
【发布时间】:2016-06-02 04:55:10
【问题描述】:

是否可以修改作为数组的父 public var,以便在子类中包含更多项目?

现在我只是在物理上重复父数组,然后向其中添加一些项目:

class A {
    public $arr = ['hello'];
}

class B extends A {
    public $arr = ['hello','world']; //wanna get rid of 'hello' and use parent
}

【问题讨论】:

标签: php oop


【解决方案1】:

字段声明应命名为$arr,而不是arr。而且,您不应该在子类中重新声明相同的字段。您可以在构造函数中更改它:

class A {
    public $arr = ['hello'];
}

class B extends A {
    public function __construct() {
        $this->arr []= 'world';
    }
}

一个小测试:

$a = new A(); print_r( $a->arr );
$b = new B(); print_r( $b->arr );

产生:

Array
(
    [0] => hello
)
Array
(
    [0] => hello
    [1] => world
)

【讨论】:

  • 这是正确答案,但需要快速修复。构造函数上缺少右括号。
  • 感谢@JamesWiley,已修复!
  • 谢谢。正在写关于 $this->arr [] = ['world'] 的评论,但你也已经修复了它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-15
  • 1970-01-01
  • 2014-12-03
  • 1970-01-01
  • 1970-01-01
  • 2015-04-07
  • 2014-02-17
相关资源
最近更新 更多