2014-12-02 28 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。建议 - 在私人方面犯错,除非你有理由不这样做。