如何通过合并数组继承父类数组属性?

Rea*_*lar 4 php cakephp cakephp-2.2

我经常在我的类中使用存储一系列选项的属性.我希望能够以某种方式合并父类中声明的默认选项.

我演示了一些代码.

class A
{
    public $options = array('display'=>false,'name'=>'John');
}

class B extends A
{
    public $options = array('name'=>'Mathew');
}
Run Code Online (Sandbox Code Playgroud)

现在当我创建时B,我想要$options包含一个合并的数组A::options

现在发生的是这个.

$b = new B();
print_r($b);
array('name'=>'Mathew');
Run Code Online (Sandbox Code Playgroud)

我想要这样的东西array_merge_recursive().

array('display'=>false,'name'=>'Mathew');
Run Code Online (Sandbox Code Playgroud)
  • 也许这是我在构造函数中可以做的事情?
  • 是否有可能使这成为一种行为class A?因此,我并不总是必须在所有子类中实现相同的代码.
  • 我可以使用反射在两个类中自动查找数组属性并合并它们吗?

Syn*_*xis 6

除了之前的答案,另一种可能适用于某些情况的方法是使用PHP Reflection或内置类函数.以下是使用后者的基本示例:

class Organism
{
    public $settings;
    public $defaults = [
        'living' => true,
        'neocortex' => false,
    ];
    public function __construct($options = [])
    {
        $class = get_called_class();
        while ($class = get_parent_class($class)) {
            $this->defaults += get_class_vars($class)['defaults'];
        }
        $this->settings = $options + $this->defaults;
    }
}
class Animal extends Organism
{
    public $defaults = [
        'motile' => true,
    ];
}
class Mammal extends Animal
{
    public $defaults = [
        'neocortex' => true,
    ];
}

$fish = new Animal();
print_r($fish->settings); // motile: true, living: true, neocortex: false
$human = new Mammal(['speech' => true]);
print_r($human->settings); // motile: true, living: true, neocortex: true, speech: true
Run Code Online (Sandbox Code Playgroud)


goa*_*oat 5

我意识到我将您的接口从公共变量更改为方法,但也许它适合您。setOps($ops)请注意,如果您允许继续合并父操作,则添加简单方法可能会产生意想不到的效果。

class A
{
    private $ops = array('display'=>false, 'name'=>'John');
    public function getops() { return $this->ops; }
}
class B extends A
{
    private $ops = array('name'=>'Mathew');
    public function getops() { return array_merge(parent::getOps(), $this->ops); }
}
class c extends B
{
    private $ops = array('c'=>'c');
    public function getops() { return array_merge(parent::getOps(), $this->ops); }
}

$c = new C();
print_r($c->getops());
Run Code Online (Sandbox Code Playgroud)

出去:

Array
(
    [display] => 
    [name] => Mathew
    [c] => c
)
Run Code Online (Sandbox Code Playgroud)