附加到PHP中父类的数组变量

时间:2008-10-22 00:50:55

标签: php oop

如何在PHP中扩展父类的子类选项数组?

我有这样的事情:

class ParentClass {

     public $options = array(
          'option1'=>'setting1'
     );

     //The rest of the functions would follow
}

我想在子类中追加该选项数组而不删除任何父选项。我尝试过做这样的事情,但还没有完成它的工作:

class ChildClass extends ParentClass {

     public $options = parent::options + array(
          'option2'=>'setting2'
     );

     //The rest of the functions would follow
}

做这样的事情最好的方法是什么?

3 个答案:

答案 0 :(得分:8)

我认为最好在构造函数中初始化此属性,然后可以在任何后代类中扩展该值:

<?php
class ParentClass {

    public $options;
    public function __construct() {
        $this->options = array(
            'option1'=>'setting1'
        );
    }
    //The rest of the functions would follow
}

class ChildClass extends ParentClass {
    public function __construct() {
        parent::__construct();
        $this->options['option2'] = 'setting2';
    }
    //The rest of the functions would follow
}
?>

答案 1 :(得分:1)

PHP或不,您应该有一个访问者来执行此操作,因此您可以调用$self->append_elements( 'foo' => 'bar' );而不用担心内部实现。

答案 2 :(得分:1)

你可以array_merge吗?

假设您使用ctr创建类。

E.g。

public function __construct(array $foo)
{
  $this->options = array_merge(parent::$options, $foo);
}