Douglas Silva
Douglas Silva

Reputation: 345

Parent's protected properties inaccessible to child object

I have a parent class I'll be calling 'ParentClass' and a child class (that extends from it) which I'll be calling 'ChildClass'.

I have already tested the properties at the parent class with var_dump($this->prop1). It returns the value I'm expecting.

However, if I var_dump($this->prop1) from the child class, I get NULL.

class ParentClass {

    protected $prop1;

    protected $prop2;

    public function __construct($prop1, $prop2) {

        $this->prop1 = $prop1;

        $this->prop2 = $prop2;

    }

    public function fakeMethod() {

        $child = new ChildClass;
        $child->anotherFakeMethod();

        // logic

    }

}
class ChildClass extends ParentClass {

    public function __construct() {

        // this overrides the parent constructor

    }

    public function anotherFakeMethod() {

        $prop1 = $this->prop1;
        $prop2 = $this->prop2;

        var_dump($this->prop1);
        // returns NULL

    }

}

Why can't the child class access the parent class' properties if it extends from it?

Upvotes: 0

Views: 573

Answers (1)

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21681

They are accessible, but they will be null because they are not passed to the parent constructor from the child:

(new ChildClass(1,2))->anotherFakeMethod();

Sandbox

Output

NULL

Your classes produce the expected result of null in this case. Well it produces what I would expect it to based on how it's coded.

To fix it, you must pass that data back to the parent class through the child's constructor, or remove the child's constructor. Like this:

class ChildClass extends ParentClass {

    public function __construct($prop1, $prop2) {
         parent::__construct($prop1, $prop2);
    }
....
}

After the above change:

(new ChildClass(1,2))->anotherFakeMethod();

Output

int(1)

Sandbox

Which is what I would expect from this line as it's basically the first argument used in the constructor:

var_dump($this->prop1);

You can also do it this way, if you know what they are in the child class:

public function __construct() {
     parent::__construct(1, 2); //say I know what these are for this child
}

You could of course set them manually in the new constructor but that would be WET (write everything twice) or unnecessary duplication, in this case.

Cheers!

Upvotes: 1

Related Questions