Get an instance of the class of the calling object 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 find out that "" $ this-> barInstance-> fooInstance = $ this; "

+4
source share
1 answer

In theory, you could do this with debug_backtrace() , which are like objects in a stack trace, but it’s better not to do this, this is not a good encoding. I think the best way for you is to pass the parent object to 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 the correct type ( Foo ), removes the type if it is not what you want. Passing it to ctor would ensure that Bar would never be able to when doSomethingWithFoo() fails.

+3
source

Source: https://habr.com/ru/post/1337633/


All Articles