Amin Abdolrezapoor
Amin Abdolrezapoor

Reputation: 1847

Can't access parent class properties

When i use parent class properties it returns NULL , I have no idea why this happens, Example code :

class Foo
{

    public $example_property;

    public function __construct(){
        $this->example_property = $this->get_data();
    }

    public function get_data() {
        return 22; // this is processed dynamically.
    }
}

class Bar extends Foo
{
    public function __construct(){}

    public function Some_method() {
        return $this->example_property; // Outputs NULL
    }
}

Actually it happens when i set property values with constructor , But if i set values staticly ( e.g : public $example_property = 22 , It won't return NULL any more

Upvotes: 1

Views: 229

Answers (1)

u_mulder
u_mulder

Reputation: 54831

This happens because parent constructor should be called explicitly:

class Bar extends Foo
{
    public function __construct() {
        parent::__construct();
    }


    public function Some_method() {
        return $this->example_property; // Outputs NULL
    }
}

But looking closer - if you don't declare Bar constructor, parent one should be executed. Maybe you don't show us full code?

So, if you have __construct in a child class and want to use parent constructor - you should call it explicitly, as I said as parent::__construct();.

If you don't have __construct method in a child class, parent's one will be called.

Upvotes: 3

Related Questions