我有一個ParentClass,當我做一個新的對象,我想傳遞一個對ParentClass的引用。 (我必須在新對象中使用ParentClass事物)PHP引用傳遞使對象的新實例?
我使用構造函數來創建此對象並傳遞參考值。 (這對我很重要)
但是,當我使用=&
運算符時,它創建了一個新的ParentClass實例,調用構造函數,然後它是一個無盡的遞歸。
這裏是我的代碼:
<?php
abstract class MainClass {
function __construct(&$parent){
$this->parent =& $parent;
$this->init();
}
abstract protected function init();
}
class ParentClass extends MainClass {
protected function init(){
$this->child = new ChildClass($this);
}
}
class ChildClass extends MainClass {
protected function init(){}
}
$parent = new ParentClass (new stdClass());
var_dump($parent);
?>
而結果:
object(ParentClass)#1 (2) {
["parent"]=>
object(stdClass)#2 (0) {
}
["child"]=>
object(ChildClass)#3 (1) {
["parent"]=>
object(ParentClass)#1 (2) {
["parent"]=>
object(stdClass)#2 (0) {
}
["child"]=>
object(ChildClass)#3 (1) {
["parent"]=>
*RECURSION*
}
}
}
}
我怎樣才能解決這個問題?
你說得對!另一個函數使我的代碼中的無限循環。 在這種情況下,沒有遞歸。謝謝! – SadAir 2011-06-16 08:24:12
+1,但小的更正:對象不通過引用傳遞。它們的行爲更像資源,其中變量只包含對其所持對象的引用,但它不是引用本身。這種差異可能聽起來微不足道,但影響相當大;如果對象通過引用傳遞,那麼下面的代碼將以不同的方式工作:http://ideone.com/04PNf – 2011-06-16 08:29:33
@reko:我明白你的觀點,你是對的。在這方面我有點粗心;) – 2011-06-16 08:36:50