2011-06-16 21 views
0

我有一個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* 
     } 
    } 
    } 
} 

我怎樣才能解決這個問題?

回答

2

默認情況下,通過引用傳遞對象。沒有理由通過引用來傳遞或分配$parent。所以這應該是足夠了:

abstract class MainClass { 

    function __construct($parent){ 
     $this->parent = $parent; 
     $this->init(); 
    } 

這可能是重要的是你使用&$parent,但它是完全沒有必要的。


關於遞歸:有一個在你的代碼沒有遞歸,它是在輸出遞歸。

這一部分:

object(ChildClass)#3 (1) {    // <--- the same element 
    ["parent"]=> 
    object(ParentClass)#1 (2) { 
     ["parent"]=> 
     object(stdClass)#2 (0) { 
     } 
     ["child"]=> 
     object(ChildClass)#3 (1) {   // <--- the same element 
     ["parent"]=> 
     *RECURSION* 
     } 
    } 
    } 

將被打印一遍又一遍,因爲孩子有其父及其父其子基準的基準。

也許更明顯是重複數字輸出:

object(ParentClass)#1   // 1 
    object(stdClass)#2    // 2 
    object(ChildClass)#3   // 3 
    object(ParentClass)#1  // 1 
     object(stdClass)#2   // 2 
     object(ChildClass)#3  // 3 
     // what would be here? right, object(ParentClass)#1 again 

這是正常的,沒有問題。

+0

你說得對!另一個函數使我的代碼中的無限循環。 在這種情況下,沒有遞歸。謝謝! – SadAir 2011-06-16 08:24:12

+1

+1,但小的更正:對象不通過引用傳遞。它們的行爲更像資源,其中變量只包含對其所持對象的引用,但它不是引用本身。這種差異可能聽起來微不足道,但影響相當大;如果對象通過引用傳遞,那麼下面的代碼將以不同的方式工作:http://ideone.com/04PNf – 2011-06-16 08:29:33

+0

@reko:我明白你的觀點,你是對的。在這方面我有點粗心;) – 2011-06-16 08:36:50

0

更好的設計。

你不應該需要對父類的引用。如果有需要類似的方法,那麼它們應該是覆蓋所有子對象的靜態方法。

相關問題