【发布时间】:2015-04-15 10:27:52
【问题描述】:
从 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->variable 来为所有扩展类返回 bar。经过研究,最推荐的解决方案是为子 __construct 中的每个类调用 __construct 方法,但这在这种情况下不起作用,因为正在调用子类来自父类。
有人可以帮忙吗?谢谢:)
【问题讨论】:
-
您应该在派生类构造函数中调用
parent::__construct。这将调用父构造函数并将$this->variable设置为bar。
标签: php class variables dynamic