Search code examples
phpclassabstract-classparentself

PHP parent::$property returned instead of self:$property when using parent method


I am trying to create a abstract class that has a property/array of settings and then in the child classes add additional properties to that property/array. I want methods defined in the abstract class to use the child classes property/array when the method is called from the child. I thought the code bellow should work... But it seems to still be accessing the property from the parent class.

abstract class AbstractClass {

    protected static $myProp;

    public function __construct() {
        self::$myProp = array(
            'a' => 10,
            'b' => 20
        );
    }

    protected function my_print() {
        print_r( self::$myProp );
    }

}

class ClassA extends AbstractClass {

    protected static $myProp;

    public function __construct() {
        parent::__construct();
        self::$myProp = array_merge( parent::$myProp, 
            array(
                'c' => 30,
                'd' => 40
            )
        );
        $this->my_print( self::$myProp );
    }

}

$myObj = new ClassA;

This should return Array ( [a] => 10 [b] => 20 [c] => 30 [d] => 40 ) Instead it returns Array ( [a] => 10 [b] => 20 )

How do I get this to work?!?


Solution

  • Actually in parent class you did not define method my_print() to contain any arguments, plus, the method uses self::$myProp (not static::). Also, as Ka_lin already answered you do not need to redeclare property that has been declared in parent class.

    If you do (for some reason need to redeclare it like set predefined value different than parent) you can do two things:
    For one, you can change my_print() to accept argument then print_r() the argument not self::$myProp:

    protected function my_print($debug) {
         print_r($debug);
    }
    

    Or, (in PHP as of version 5.3.0.) you can use static:: instead of self:::

    protected function my_print() {
         print_r(static::$myProp);
    }
    

    I would go for the second option.
    Also you should ready more about self vs static (late binding) in php manual