|  | Posted by Janwillem Borleffs on 06/05/05 15:24 
L Robbins wrote:> Given that the names of the objects are predictable, it
 > would be possible for me to write some code which looped sequentially
 > through the object names $object1, $object2, etc., until it reached
 > an object name which didn't exist. However, I was expecting there to
 > be a tidier, easier way of doing the same thing with a command that
 > says simply "List all instances of class X."
 >
 > Could you please tell me how to do this, or why it is not possible?
 
 There is no function that returns all the instances of a class. If you want
 to keep track of them, you could store them in an array or loop through the
 $GLOBALS array and test each key with is_object() and instanceof (or is_a()
 when not using PHP5).
 
 When using PHP5, you could also keep track of all created instances as
 follows:
 
 <?php
 
 class Foo {
 private static $instance_count = 0;
 public static function getInstanceCount() {
 return self::$instance_count;
 }
 
 function __construct() {
 self::$instance_count++;
 }
 
 function __destruct() {
 self::$instance_count--;
 }
 }
 
 $foo = new Foo;
 print Foo::getInstanceCount(); // 1
 
 unset($foo);
 print Foo::getInstanceCount(); // 0
 
 ?>
 
 
 JW
 [Back to original message] |