「T不會是我的代碼是(不同的構造函數簽名)感到驕傲,但是這會工作(一次性使用):
class base{
public $c = 'c';
public $sub = '';
function __construct(){
$this->sub = new sub($this);
}
}
class sub extends base{
public $ab = 'abs';
function __construct($parent){
$parent->c = 'aas';
echo 'Test';
}
}
如果你需要更經常地:
class base{
private $parent;
private $top;
public $c = 'c';
public $sub = '';
function __construct(base $parent = null, base $top = null){
$this->parent = $parent;
$this->top = $top;
$this->addSub();
}
function addSub(){
$this->sub = new sub($this,$this->top ? $this->top : $this);
}
}
class sub extends base{
public $ab = 'abs';
function __construct($parent,$top){
parent::__construct($parent,$top);
$this->parent->c = 'aas';
}
function foo($bar){
$this->top->c = $bar;
}
//preventing infinite recursion....
function addSub(){
}
}
根據實際需要,另一種設計模式可能更適合。
它看起來像我混淆了**繼承**(孩子延伸父母)和**構成**(一個對象持有對另一個引用)的概念。但也許不是。你能解釋你爲什麼要做這種事嗎? – grossvogel 2010-09-15 23:02:34