tags:

views:

39

answers:

2

Hi guys, 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!

+3  A: 

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;
...
Xian
Xian this works. However I need a more global approach, perhaps another class that tracks every new Object(); call without requiring to add a reference in every constructor of every object. Thanks!
Juank
Seems to me that Xian gave the answer to the question you asked: each car knows which engine instance it created, each engine knows by which car instance it was created. Perhaps you meant to ask a different question?
Elise van Looij
A: 

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.

Gordon