May 4, 2012

accessing parent property values in child class

Question by Eli

I have a strange issue where I set values in a parent class but cannot access those values in a child class extending the parent.

class Parent
{
    protected $config;

    public function load($app)
    {
        $this->_config();
        $this->_load($app);
    }

    private function _config()
    {
        $this->config = $config; //this holds the config values
    }

    private function _load($app)
    {
        $app = new $app();
        $this->index;
    }
}

class Child extends Parent
{
    public function index()
    {
        print_r($this->config); // returns an empty array
    }
}

$test = new Parent();
$test->load('app');

when I do that i get an empty array printed out. But if I do this then I am able to access those config values.

private function _load($app)
{
    $app = new $app();
    $app->config = $this->config
    $app->index;

}

and

class Child extends Parent
{
    public $config;
          ....
}

then I can access the config data from the parent.

Answer by Starx

You are accessing the values before anything is initialized there. First you have to set the values.

Example: call a method is the parent class, which set the value, on the contructor of the child class.

class Child extends Parent
{
    public function __construct() {
       $this -> setConfig(); //call some parent method to set the config first
    }
    public function index()
    {
        print_r($this->config); // returns an empty array
    }
}

Update: You also seem to confused about concept of OOP

class Parent { ..... }
class child extends Parent { ..... }
$p = new Parent(); // will contain all method and properties of parent class only
$c = new Child(); // will contain all method and properties of child class and parent class

But, you have to work with parent methods and properties just the same way you would do in the normal object.

Lets See another example:

class Parent { 
     protected $config = "config";
}
class Child extends Parent {
     public function index() {
           echo $this -> config; // THis will successfully echo "config" from the parent class
     }
}    

But another example

class Parent { 
     protected $config;
}
class Child extends Parent {
     public function index() {
           echo $this -> config; //It call upon the parent's $config, but so far there has been no attempt to set an values on it, so it will give empty output.
     }
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!