2014-12-02 30 views
0

我有一個外部類有另一個類作爲成員(遵循繼承的原則組成)。現在我需要從內部類中調用外部類的方法。課程組成 - 從內部類呼叫外部方法

class Outer 
{ 
    var $inner; 
    __construct(Inner $inner) { 
     $this->inner = $inner; 
    } 
    function outerMethod(); 
} 
class Inner 
{ 
    function innerMethod(){ 
// here I need to call outerMethod() 
    } 
} 

我看到作爲解決在外層中添加參考:: __構建體:

$this->inner->outer = $this; 

這允許我打電話內蒙古這樣外方法:: innerMethod:

$this->outer->outerMethod(); 

這是一個很好的解決方案還是有更好的選擇?

+0

是否有內部類調用外部的特定原因?爲什麼不像內部調用外部方法作爲參數,以免創建循環依賴關係? – 2014-12-02 12:39:58

+0

原因是:內部類是外部的專業化。有幾個可能的類實現InnerInterface。外部類包含不變的方法,內部類包含特定於特定的方法。 – 2014-12-02 12:50:48

回答

1

最好的辦法是將外部類包含爲內部成員變量。

E.g.

class Inner 
{ 
    private $outer; 
    function __construct(Outer $outer) { 
     $this->outer= $outer; 
    } 
    function innerMethod(){ 
// here I need to call outerMethod() 
     $this->outer->outerMethod(); 
    } 
} 

如果這是不可能構造內與外開始,你可以把內一個setOuter方法,並調用它,當你把它傳遞到Outer

E.g.

class Outer 
{ 
    private $inner; 
    function __construct(Inner $inner) { 
     $inner->setOuter($this); 
     $this->inner = $inner; 
    } 
    function outerMethod(); 
} 

class Inner 
{ 
    private $outer; 
    function setOuter(Outer $outer) { 
     $this->outer= $outer; 
    } 
    function innerMethod(){ 
// here I need to call outerMethod() 
     $this->outer->outerMethod(); 
    } 
} 

注意:var作爲成員變量類型的規範已被棄用。改爲使用publicprotectedprivate。建議 - 在私人方面犯錯,除非你有理由不這樣做。