Juank
Juank

Reputation: 6196

How can I get the instance that created another object's instance in php?

I need to track which instance created another instance. It's an instancing hierarchy not a parent-child class hierarchy. Here's an example:

class Car{

    private var $engine;
    private var $id;

    public function __construct(){
        $this->id = nextId();
        $this->engine = new Engine(500);
    }
}

class Engine{

    private var $horsepower;
    private var $id;

    public function __construct($hp){
        $this->id = nextId();
        $this->horsepower = $hp;
    }
}

if I do:

$myCar1 = new Car();
$myEngine = new Engine(200);

I currently have 1 instance of Car and 2 of Engine. I need to know which instance created which instance. something like this:

$creator = instanceCreatorOf($myCar1->engine or $myCar1->engine->id);

would return: $myCar or $myCar->id;

but if I do:

$creator = instanceCreatorOf($myEngine or $myEngine->id);

would return: root or null or 0;

I need to track this but having a lot of dynamically created objects I need dynamic tracking of this hierarchy. Any ideas? thanks!

Upvotes: 0

Views: 117

Answers (2)

Gordon
Gordon

Reputation: 317119

You'd have to look at the debug_backtrace once the instance is created. From there you could store the creator in a variable, as there is no way to do that later. Thus, I'd also suggest passing the creating instance to the other instance if they are conceptually tied together. And Cars and their Engines are.

Upvotes: 0

Xian Stannard
Xian Stannard

Reputation: 376

Can you have an Car create its own engine and pass in a reference to itself:

class Car {
  function __construct() {
    myEngine = new Engine(this);
...

and

class Engine {
 var $creator;
 function __construct(Car $car, $horsepower) {
  $this->creator = $car;
...

Upvotes: 3

Related Questions