类组合 - 从内部类调用外部方法


Class composition - Call outer method from inner class

>我有一个外部类,它有另一个类作为成员(遵循继承的原则组合(。现在我需要从内部的类调用外部类的方法。

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

我认为在 Outer::__construct 中添加引用是一种解决方案:

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

这允许我在 Inner::innerMethod 中像这样调用外部方法:

$this->outer->outerMethod();

这是一个好的解决方案还是有更好的选择?

最好的主意是将外部类作为内部类的成员变量包含在内。

例如

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

如果最初无法用外部构造内部,则可以在内部放置一个setOuter方法,并在将其传递到Outer时调用它。

例如

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作为规范作为 membed 变量类型。 请改用publicprotectedprivate。 建议 - 除非你有理由不这样做,否则在私人方面犯错。