如何防止重写PHP类中的父属性?
我是PHP OOP的初学者。我想防止在子类启动时重写父类属性。例如,我有如何防止重写PHP类中的父属性?,php,class,oop,inheritance,php-7,Php,Class,Oop,Inheritance,Php 7,我是PHP OOP的初学者。我想防止在子类启动时重写父类属性。例如,我有Parent和Child类,如下所示: class Parent { protected $array = []; public function __construct() { } public function add($value) { $this->array[] = $value; } public function get() {
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 = new Child;
$child->add('d');
然后,我启动了Child
类,并向array
属性添加了1项:
$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')
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();
}
}
在这里,扩展类似乎不是您想要做的事情 您应该了解类和对象之间的区别。也许你应该先做一个通用的OOP教程 如果希望在类的实例之间共享静态变量,则需要使用静态变量。您应该这样做
$child = clone $parent;
$child->add('d');
我是用静态变量做的。我现在的课程是这样的:
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')
孩子!=父类,仅仅因为它扩展了,它仍然是两个独立的实例。@treyBake,那么我如何在启动时将一些属性传递给子类?child扩展了父类,但如果您实例化父类,它与child没有连接只是实例化子类而不是父类如果您总是想将同一组属性传递给子类,您可以在父类中将它们设置为默认值。不,类定义对象的工作方式。对象是从类实例化的。有些特殊的语言,如Smalltalk,其中类也是对象,但通常类本身只是保存在文本文件中的定义,而不是“活动”对象。