tags:

views:

49

answers:

2

I've got a php class that I create several instances for. I'd like to get a count of how many times I've created that object.

<?php
     class myObject {
         //do stuff
     }

    $object1 = new myObject;
    $object2 = new myObject;
    $object3 = new myObject;
?>

Is there a way to find that I've created 3 myObjects?

+7  A: 

You can create a static counter and increment it each time your constructor is called.

<?php
class BaseClass {
    public static $counter = 0;

    function __construct() {
        self::$counter++;
    }
}

new BaseClass();
new BaseClass();
new BaseClass();

echo BaseClass::$counter;
?>

This code on ideone

Colin Hebert
Perfect. Thanks!
joeybaker
if you also want to take cloned and unserialized instances into account, add the magic `__clone` and `__wakeup` methods and increment the counter in them as well.
Gordon
+1  A: 

If your class has a __construct() function defined, it will be run every time an instance is created. You could have that function increment a class variable.

Nathan Long
D'oh! Too slow. :)
Nathan Long
Can you provide an example?
Galen