【问题标题】:How to prevent overriding of parent properties in a PHP class?如何防止覆盖 PHP 类中的父属性?
【发布时间】:2019-09-13 21:58:42
【问题描述】:

我是 PHP OOP 的初学者。我想防止在子类启动时覆盖父类属性。比如我有ParentChildclasses如下:

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

首先,我发起Parentclass向array属性添加了3项:

$parent = new Parent;
$parent->add('a');
$parent->add('b');
$parent->add('c');

然后,我启动了Child 类并在array 属性中添加了一项:

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

【问题讨论】:

  • child != parent,只是因为它扩展,它仍然是两个独立的实例。
  • @treyBake,那么如何在启动时将一些属性传递给子类?
  • 子扩展父,但如果你实例化父它与子没有联系
  • 只实例化孩子而不是父母
  • 如果你总是想将相同的属性集传递给子类,你可以在父类中将它们设置为默认值。

标签: php class oop inheritance php-7


【解决方案1】:

我是用静态变量来做的。我的课现在是这样的:

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

【讨论】:

    【解决方案2】:

    你应该这样做。

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

    【讨论】:

      【解决方案3】:

      看来扩展一个类不是你要在这里做的。

      您应该了解类和对象之间的区别。也许你应该先做一个通用的 OOP 教程。

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

      【讨论】:

      • 没有一个类定义了对象的工作方式。该对象是从类中实例化的。有像 Smalltalk 这样的特殊语言,其中类也是对象,但通常类本身只是保存在文本文件中的定义,而不是“活”对象。 dev.to/charanrajgolla/…
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多