Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/232.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 类组合-从内部类调用外部方法_Php_Oop_Composition - Fatal编程技术网

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

Php 类组合-从内部类调用外部方法,php,oop,composition,Php,Oop,Composition,我有一个外部类,它有另一个类作为成员(遵循组合优先于继承的原则)。现在我需要从内部的类调用外部类的方法 class Outer { var $inner; __construct(Inner $inner) { $this->inner = $inner; } function outerMethod(); } class Inner { function innerMethod(){ // here I need to call o

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

class Outer
{
    var $inner;
    __construct(Inner $inner) {
        $this->inner = $inner;
    }
    function outerMethod();
}
class Inner
{
    function innerMethod(){
// here I need to call outerMethod()
    }
}
我认为在Outer::u构造中添加引用是一种解决方案:

$this->inner->outer = $this;
这允许我在Inner::innerMethod中调用如下外部方法:

$this->outer->outerMethod();

这是一个好的解决方案还是有更好的替代方案?

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

例如

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

例如


注意:
var
作为membed变量类型的规范已被弃用。使用
public
protected
private
。建议-除非您有理由不这样做,否则会在private方面出错。

内部类调用外部类是否有特定的原因?为什么不调用外部方法,将内部作为参数,这样就不会创建循环依赖关系呢?原因是:内部类是外部类的特殊化。有几个可能的类实现InnerInterface。外部类包含不变的方法,内部类包含特定于专业化的方法。
class Inner
{
    private $outer;
    function __construct(Outer $outer) {
        $this->outer= $outer;
    }
    function innerMethod(){
// here I need to call outerMethod()
       $this->outer->outerMethod();
    }
}
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();
    }
}