简体   繁体   English

从另一个对象获取调用者类实例

[英]Get a caller class instance from another object

Please take a look at this code: 请看一下这段代码:

class Foo {

   public $barInstance;

   public function test() {
      $this->barInstance = new Bar();
      $this->barInstance->fooInstance = $this;
      $this->barInstance->doSomethingWithFoo();
   }

}

class Bar {
   public $fooInstance;

   public function doSomethingWithFoo() {
       $this->fooInstance->something();
   }
}

$foo = new Foo();
$foo->test();

Question: is it possible to let the " $barInstance" know from which class it was created (or called) without having the following string: "$this->barInstance->fooInstance = $this;" 问题:是否可以让“ $barInstance"知道它是从哪个类创建(或调用)而没有以下字符串: "$this->barInstance->fooInstance = $this;"

In theory, you might be able to do it with debug_backtrace() , which as objects in the stack trace, but you better not do it, it's not good coding. 从理论上讲,您可以使用debug_backtrace()作为堆栈跟踪中的对象,但最好不要这样做,这不是很好的编码。 I think the best way for you would be to pass the parent object in Bar's ctor: 我认为最好的方法是在Bar的ctor中传递父对象:

class Foo {

    public $barInstance;

    public function test() {
       $this->barInstance = new Bar($this);
       $this->barInstance->doSomethingWithFoo();
    }
}

class Bar {
    protected $fooInstance;

    public function __construct(Foo $parent) {
         $this->fooInstance = $parent;
    }

    public function doSomethingWithFoo() {
        $this->fooInstance->something();
    }
}

This limits the argument to being proper type ( Foo ), remove the type if it's not what you want. 这会将参数限制为正确的类型( Foo ),如果不是您想要的类型,则删除该类型。 Passing it in the ctor would ensure Bar is never in the state when doSomethingWithFoo() would fail. 将它传递给ctor将确保BardoSomethingWithFoo()失败时永远不会处于状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM