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:
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 ensureBaris never in the state whendoSomethingWithFoo()would fail.