开发者

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;"


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. I think the best way for you would be to pass the parent object in Bar's 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. Passing it in the ctor would ensure Bar is never in the state when doSomethingWithFoo() would fail.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜