PHP: How to call private values of parent construct in child construct?

user614972 picture user614972 · Mar 28, 2011 · Viewed 7.2k times · Source

I want to be able to set a private attribute's value in the parent constructor, and call the value in a child's constructor or method.

For example:

<?php


abstract class MainClass
{
    private $prop_1;
    private $prop_2;


     function __construct()
     {
            $this->prop_2 = 'this is  the "prop_2" property';
     }
}

class SubClass extends MainClass
{
    function __construct()
    {
        parent::__construct();
        $this->prop_1 = 'this is the "prop_1" property';
    }

    public function GetBothProperties()
    {
        return array($this->prop_1, $this->prop_2);
    }

}

$subclass = new SubClass();
print_r($subclass->GetBothProperties());

?>

Output:

Array
(
    [0] => this is the "prop_1" property
    [1] => 
)

However, if I change prop_2 to protected, the output will be:

Array
(
    [0] => this is the "prop_1" property
    [1] => this is  the "prop_2" property
)

I have basic knowledge of OO and php, but I can't figure out what is preventing prop_2 from being called (or shown?) when it's private; it can't be a private/public/protected issue, since 'prop_1' is private and able to be called and shown... right?

Is it an issue of assigning the values in the child class vs parent class?

I would appreciate help in understanding why.

Thank you.

Answer

Gaurav picture Gaurav · Mar 28, 2011

Private properties of parent class can not be accessed in Child class and vice versa.

You can do like this

abstract class MainClass
{
   private $prop_1;
   private $prop_2;


   function __construct()
   {
        $this->prop_2 = 'this is  the "prop_2" property';
   }

   protected function set($name, $value)
   {
        $this->$name = $value;
   }

   protected function get($name)
   {
      return $this->$name;
   }

 }


class SubClass extends MainClass
{
    function __construct()
    {
        parent::__construct();
        $this->set('prop_1','this is the "prop_1" property');
    }

    public function GetBothProperties()
    {
        return array($this->get('prop_1'), $this->get('prop_2'));
    }

}