如何在php中获取创建另一个对象实例的实例?

[英]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:

我目前有1个Car实例和2个Engine实例。我需要知道哪个实例创建了哪个实例。像这样的东西:

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

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

将返回:$ myCar或$ myCar-> id;

but if I do:

但如果我这样做:

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

would return: root or null or 0;

将返回:root或null或0;

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

我需要跟踪这个但是有很多动态创建的对象我需要动态跟踪这个层次结构。有任何想法吗?谢谢!

2 个解决方案

#1


3  

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

你有没有Car创建自己的引擎并传递给自己的引用:

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

and

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

#2


0  

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.

创建实例后,您必须查看debug_backtrace。从那里你可以将创建者存储在变量中,因为以后无法做到这一点。因此,如果它们在概念上绑在一起,我还建议将创建实例传递给另一个实例。而汽车及其发动机则是。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2010/01/04/f91ab32543d54956a004ac992646618b.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号