phpcakephpcakephp-2.2

How to inherit parent class array properties by merging array?


I often use properties in my classes that store an array of options. I'd like to be able to somehow merge those options from defaults declared in a parent class.

I demonstrated with some code.

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

class B extends A
{
    public $options = array('name'=>'Mathew');
}

Now when I create B, then I'd like $options to contain a merged array from A::options

What happens now is this.

$b = new B();
print_r($b);
array('name'=>'Mathew');

I would like something like this using array_merge_recursive().

array('display'=>false,'name'=>'Mathew');

Solution

  • I realize I changed your interface from a public variable to a method, but maybe it works for you. Beware, adding a naive setOps($ops) method may work unexpected if you allow the parent ops to continue to be merged in.

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

    out:

    Array
    (
        [display] => 
        [name] => Mathew
        [c] => c
    )