Vincent
Vincent

Reputation: 1730

Undefined property when accessing properties from a parent class

I can't figure out how to access a property from class A using class B when class B is a child of class A and should inherits its properties using "extends".

Basically, I have:

class A{
    function __construct(){
        $this->foo = 'foo';
    }
}

class B extends A{
    function __construct(){
    }
}

Now, using

$B_obj = new B();
echo $B_obj->foo;

Returns

Notice: Undefined property B::$foo

I know I should put "protected" somewhere: I tried in front of the construct function in class A but it did not work.

Thanks for your precious help

Upvotes: 2

Views: 1391

Answers (1)

Jonan
Jonan

Reputation: 2536

put this in the constructor of class B()

parent::__construct();

this basically runs the constructor of the parent

Upvotes: 1

Related Questions