【问题标题】:Class composition - Call outer method from inner class类组合 - 从内部类调用外部方法
【发布时间】:2023-03-23 22:25:02
【问题描述】:

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

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

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

【问题讨论】:

  • 内部类调用外部类是否有特定原因?为什么不使用内部作为参数调用外部方法,以免创建循环依赖?
  • 原因是:内部类是外部类的特化。有几个可能的类实现了 InnerInterface。外部类包含不变的方法,内部类包含专门化的特定方法。

标签: php oop composition


【解决方案1】:

最好的办法是将外部类作为内部的成员变量。

例如

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 作为一个规范的成员变量类型已被弃用。请改用publicprotectedprivate。建议 - 私下犯错,除非你有理由不这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-16
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    相关资源
    最近更新 更多