Singleton:
class SingletonClass {
private static $instance;
private function __construct() { }
public function __clone() {
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
public static function init() {
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
// other public, dynamic methods for singleton
}
$singleton = SingletonClass::init();
Track number of instances:
class CountMe {
public static $instances = 0;
public function __construct() {
CountMe::$instances++;
}
public function __destruct() {
CountMe::$instances--;
}
}
$a = new CountMe();
$b = new CountMe();
echo CountMe::$instances; // outputs 2
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…