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

时间:2019-04-24 14:45:26

标签: php class oop inheritance php-7

我是PHP OOP的初学者。我要防止在子类启动时覆盖父类属性。例如,我有ParentChild类,如下所示:

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();
    }
}

3 个答案:

答案 0 :(得分:0)

我使用静态变量做到了。我的课程现在是这样的:

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')

答案 1 :(得分:-1)

扩展课程似乎不是您想在这里做的。

您应该阅读有关类和对象之间的区别。也许您应该先做一个通用的OOP教程。

如果要在类的实例之间共享静态变量,则需要使用静态变量。

答案 2 :(得分:-1)

您应该这样做。

$child = clone $parent; 
$child->add('d');