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

时间:2014-12-02 12:37:12

标签: php oop composition

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

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();

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

1 个答案:

答案 0 :(得分: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。建议 - 在私人方面犯错,除非你有理由不这样做。