Reputation: 345
I have a parent class I'll be calling 'ParentClass' and a child class (that extends from it) which I'll be calling 'ChildClass'.
ParentClass has protected properties $prop1 and $prop2 which I want ChildClass to access. But I'm getting NULL from them.
ParentClass has a __construct() method which sets the properties received through dependency injection.
ParentClass instantiates ChildClass from one of its methods.
ChildClass overwrites the parent constructor, but doesn't contain any code inside of its own __construct() method.
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
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();
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)
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