从php中的扩展类访问动态父变量的最佳方式是什么?
在下面的例子中,我基本上简化了我要做的事情。我需要能够从子类访问变量'$variable'。然而,$variable在构造类A时发生更改,但对类B和C的定义没有更改。
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();
我基本上需要$this->变量来返回所有扩展类的bar。经过研究,最推荐的解决方案是为子类的__construct中的每个类调用__构造方法,但在这种情况下不起作用,因为子类是从父类调用的。
有人能伸出援手吗?感谢:)
也许这样的事情就是答案?
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();
有两个函数调用很麻烦。也许可以采用不同的设计模式?
正如@theoems所指出的,除非用parent::__construct()
显式调用父构造函数,否则不会调用它。另一种解决方法可能是使用get_called_class()
(自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();
但我想知道,你为什么要这么做?我认为如果你遇到这种情况,你的课可能会有设计缺陷。。。