Track number of objects created from a class

To track the existing number of objects of a given class create a static property to hold the current value, updated with the constructor. When unsetting an object, the __destruct() method will update the object count. You can create new instances without hitting the constructor via clone and deleted with unset()


/*
* Class TrackableClass 
*/
class TrackableClass {
    public static $instances = 0;

    public function __construct() 
    {
        self::$instances++;
    }

    public function __destruct() 
    {
        self::$instances--;
    }
	
    public function __clone() 
    {
	self::$instances++;
    }
	
    public function __unset($name)
    {
        self::$instances--;
    }
	
}

$obj1 = new TrackableClass();
$obj2 = new TrackableClass();
$obj3 = new TrackableClass();
$obj4 = clone $obj3;

echo TrackableClass::$instances; // 4
unset($obj4);
echo TrackableClass::$instances; // 3
$obj3 = null;
echo TrackableClass::$instances; // 2