如何在PHP中为子类扩展父类的选项数组?
我有这样的事情:
class ParentClass {
public $options = array(
'option1'=>'setting1'
);
//The rest of the functions would follow
}
Run Code Online (Sandbox Code Playgroud)
我想在子类中追加该选项数组而不删除任何父选项.我尝试过做这样的事情,但还没有完成它的工作:
class ChildClass extends ParentClass {
public $options = parent::options + array(
'option2'=>'setting2'
);
//The rest of the functions would follow
}
Run Code Online (Sandbox Code Playgroud)
做这样的事情最好的方法是什么?
我认为最好在构造函数中初始化此属性,然后可以在任何后代类中扩展该值:
<?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
}
?>
Run Code Online (Sandbox Code Playgroud)