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

时间:2011-01-30 03:48:34

标签: php

请看一下这段代码:

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

问题:是否可以让$barInstance"知道它是从哪个类创建(或调用)而没有以下字符串:"$this->barInstance->fooInstance = $this;"

1 个答案:

答案 0 :(得分:3)

理论上,您可以使用debug_backtrace()来实现它,它作为堆栈跟踪中的对象,但您最好不要这样做,这不是很好的编码。 我认为最好的方法是在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();
    }
}

这会将参数限制为正确的类型(Foo),如果不是您想要的类型,请删除该类型。将它传递给ctor将确保Bar永远不会处于doSomethingWithFoo()失败的状态。