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.
source share