[英]How do I access a modified parent variable within child classes in PHP
從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方法,但是由於子類都從父類叫不在這種情況下工作。
有人可以伸出援手嗎? 謝謝 :)
讓子類繼承其父代的構造函數設置變量的唯一方法是調用父代的構造函數。
也許像這樣的答案?
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();
有兩個函數調用太麻煩了。 也許要走的是另一種設計模式?
正如@theoemms指出的那樣,除非您使用parent::__construct()
顯式調用父構造函數,否則不會調用它。 另一個解決方法可能是使用get_called_class()
(從PHP 5.3開始可用get_called_class()
檢查正在實例化哪個類:
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();
但是我想知道,為什么您需要這樣做? 我認為,如果遇到這種情況,您的班級可能存在設計缺陷。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.