Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging properties of parent and child classes

I am trying to merge a property in an abstract parent class with the same property in a child class. The code looks sort of like this (except in my implementation, the property in question is an array, not an integer):

abstract class A {  
   public $foo = 1;  

   function __construct() {
       echo parent::$foo + $this->foo;    # parent::$foo NOT correct  
   }  
}  

class B extends A {
    public $foo = 2;  
}  

$obj = new B();  # Ideally should output 3  

Now I realize that parent::$foo in the constructor will not work as intended here, but how does one go about merging the property values without hardcoding the value into the constructor or creating an additional property in the parent class?

like image 311
Chiraag Mundhe Avatar asked Sep 05 '25 13:09

Chiraag Mundhe


1 Answers

In the constructor of your parent class, do something like this:

<?php

abstract class ParentClass {
    protected $foo = array(
        'bar' => 'Parent Value',
        'baz' => 'Some Other Value',
    );

    public function __construct( ) {
        $parent_vars = get_class_vars(__CLASS__);
        $this->foo = array_merge($parent_vars['foo'], $this->foo);
    }

    public function put_foo( ) {
        print_r($this->foo);
    }
}

class ChildClass extends ParentClass {
    protected $foo = array(
        'bar' => 'Child Value',
    );
}

$Instance = new ChildClass( );
$Instance->put_foo( );
// echos Array ( [bar] => Child Value [baz] => Some Other Value )

Basically, the magic comes from the get_class_vars( ) function, which will return the properties that were set in that particular class, regardless of values set in child classes.

If you want to get the ParentClass values with that function, you can do either of the following from within the ParentClass itself: get_class_vars(__CLASS__) or get_class_vars(get_class( ))

If you want to get the ChildClass values, you can do the following from within either the ParentClass, or the ChildClass: get_class_vars(get_class($this)) although this is the same as just accessing $this->var_name (obviously, this depends on variable scope).

like image 163
Benjam Avatar answered Sep 08 '25 10:09

Benjam