开发者

How can I get a list of instances of a class [duplicate]

开发者 https://www.devze.com 2023-03-30 03:51 出处:网络
This question already has answers here: Closed 11 ye开发者_JAVA技巧ars ago. Possible Duplicate: Get all instances of a class in PHP
This question already has answers here: Closed 11 ye开发者_JAVA技巧ars ago.

Possible Duplicate:

Get all instances of a class in PHP

If I have a class and create a number of instances of that class, is there a way for me to retrieve a full list of those instances via PHP? I'm using PHP 5.3.6.


No, you can't do it. You can build factory class for creation objects and store them in static array.


Add a static counter to your method, and add to it every time the constructor is used. Subtract every time destruct is called.

That should give you an idea at least of how many instances are alive.


The best way to do this regardless of language is to create a singleton arraylist of instances inside the class and add to it whenever the constructor is called.


Just add a private static variable inside the class and eacht time the constructor is called, you increment the variable. And with a public function you can get the value of the variable. :)


I'm afraid you're not able to do this. However, you can try to add instance to variable everytime you're constructing your class

function __construct(){    
    $instances[] = $this;
}


The best you can probably do is use get_defined_vars() to list all vars. You should also look into get_object_vars().

0

精彩评论

暂无评论...
验证码 换一张
取 消