2011-01-30 58 views
4

请看看下面的代码:从另一个对象获取主叫类实例

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

No.(fillin text) – mhitza 2011-01-30 03:52:17

+0

您为避免该行的动机是什么?你还没有提供。 – erisco 2011-01-30 07:17:34

回答

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()将失败的状态。

相关问题