如何防止覆盖PHP类中的父属性?

我是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();

    }

}


森林海
浏览 156回答 3
3回答

开满天机

我是用静态变量来做的。我的课程现在是这样的:class Parent {    protected static $array = [];    public function __construct() {    }    public function add($value) {        self::$array[] = $value;    }    public function get() {        return self::$array;    }}class Child extends Parent {    public function __construct() {    }}当我测试它时,我得到了我所期望的:$parent = new Parent;$parent->add('a');$parent->add('b');$parent->add('c');$child = new Child;$child->add('d');var_dump($parent->show()); // outputs array('a', 'b', 'c', 'd')var_dump($child->show()); // outputs array('a', 'b', 'c', 'd')

侃侃无极

似乎扩展课程不是您想要在这里做的。您应该阅读有关类和对象之间的区别。也许您应该先做一个通用的OOP教程。如果要在类的实例之间共享静态变量,则需要使用静态变量。

慕沐林林

您应该这样做。$child = clone $parent;  $child->add('d');
打开App,查看更多内容
随时随地看视频慕课网APP