Reputation: 23
What is the best way to access dynamic parent variables from extended classes in php?
In the example below, I have simplified essentially what I am trying to do. I need to be able to access the variable '$variable' from child classes. However, $variable changes when class A is constructed, but the definition to class B and C does not change.
class A {
protected $variable = 'foo';
public function __construct(){
$this->variable = 'bar';
echo($this->variable);
$B = new B(); //Returns 'bar'
}
}
class B extends A {
public function __construct(){
echo($this->variable); //Returns 'foo'
$C = new C();
}
}
class C extends B {
public function __construct() {
echo($this->variable); //Returns 'foo'
}
}
$A = new A();
I basically need $this->variable to return bar for all extended classes. After researching, the solution most recommended is to recall the __construct method for each class within the child's __construct, but that does not work in this situation because the child classes are being called from the parent class.
Can anybody lend a hand? Thanks :)
Upvotes: 1
Views: 1250
Reputation: 68
The only way to have child classes inherit their parent's constructor set variables is to call the parent's constructor.
Maybe something like this is the answer?
class A {
protected $variable = 'foo';
public function __construct(){
$this->variable = 'bar';
echo($this->variable);
}
public function init(){
$B = new B();
//Carry on
$B->init();
}
}
class B extends A {
public function __construct(){
parent::__construct();
echo($this->variable);
}
public function init(){
$C = new C();
//Carry on
}
}
class C extends B {
public function __construct() {
parent::__construct();
echo($this->variable);
}
}
$A = new A();
$A->init();
It's messy having two function calls. Perhaps a different design pattern is the way to go?
Upvotes: 1
Reputation: 12419
As @theoemms pointed out, the parent constructor is not called unless you call it explicitly with parent::__construct()
. Another workaround could be to check which class is being instantiated using get_called_class()
(available since PHP 5.3):
class A {
protected $variable = 'foo';
public function __construct(){
$this->variable = 'bar';
echo($this->variable);
if (get_called_class() == 'A') {
$B = new B(); //Returns 'bar'
}
}
}
class B extends A {
public function __construct(){
parent::__construct();
echo($this->variable); //Returns 'bar'
if (get_called_class() == 'B') {
$C = new C();
}
}
}
class C extends B {
public function __construct() {
parent::__construct();
echo($this->variable); //Returns 'bar'
}
}
$A = new A();
But I'm wondering, why do you need to do this? I think there might be a design flaw in your classes if you're running into this situation...
Upvotes: 1