1

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.

Community
  • 1
  • 1
Ralph M. Rivera
  • 769
  • 3
  • 12
  • 25
  • PHP does not have a function for that. You'll have to manage the instance list yourself. – mario Aug 21 '11 at 16:21

6 Answers6

4

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

Andrej
  • 7,474
  • 1
  • 19
  • 21
1

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.

Russ Clarke
  • 17,511
  • 4
  • 41
  • 45
0

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.

JSideris
  • 5,101
  • 3
  • 32
  • 50
0

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

Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453
Timothy Perez
  • 20,154
  • 8
  • 51
  • 39
0

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. :)

Abbas
  • 14,186
  • 6
  • 41
  • 72
0

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;
}
genesis
  • 50,477
  • 20
  • 96
  • 125