我是PHP OOP的初学者。我想防止在子类启动时覆盖父类属性。例如,我有 Parent和Child类,如下所示:
class Parent {
protected $array = [];
public function __construct() {
}
public function add($value) {
$this->array[] = $value;
}
public function get() {
return $this->array;
}
}
class Child extends Parent {
public function __construct() {
}
}
首先,我启动了Parent课程,向该array属性添加了3个项目:
$parent = new Parent;
$parent->add('a');
$parent->add('b');
$parent->add('c');
然后,我启动了Child类,并向该array属性添加了1个项目:
$child = new Child;
$child->add('d');
实际结果:
var_dump($parent->show()); // outputs array('a', 'b', 'c')
var_dump($child->show()); // outputs array('d')
预期结果:
var_dump($parent->show()); // outputs array('a', 'b', 'c', 'd')
var_dump($child->show()); // outputs array('a', 'b', 'c', 'd')
我怎样才能做到这一点?我试过了,但是没有用:
class Child extends Parent {
public function __construct() {
$this->array = parent::get();
}
}
开满天机
侃侃无极
慕沐林林