******************************************
Singleton Class
object(foo)#1 (0) {
}
^ Resource ID
object(foo)#1 (0) {
}
^ Resource ID
object(bar)#2 (0) {
}
^ new Resource ID of singleton bar
bool(true)
******************************************
<?php
// PHP 5 generic singleton
class Singleton
{
static $_instances = array();
protected function __construct() { }
private function __clone() {}
public static function getInstance($class)
{
if (!isset(self::$_instances[$class])) {
// self::$_instances[$class] =& new $class;
self::$_instances[$class] = new $class;
}
return self::$_instances[$class];
}
}
class foo {}
class bar {}
// ---------------------------------------------
// tests to proof
// ---------------------------------------------
echo "<pre>", str_repeat("*", 42);
echo "\nSingleton Class\n";
//usage
//Singleton::getInstance($class);
$first = Singleton::getInstance('foo');
$second = Singleton::getInstance('foo');
$bar = Singleton::getInstance('bar');
var_dump($first);
echo " ^ Resource ID \n\n";
var_dump($second);
echo " ^ Resource ID \n\n";
var_dump($bar);
echo " ^ new Resource ID of singleton bar \n\n";
var_dump($first === $second); // true
echo str_repeat("*", 42), "</pre>";
if ('cli'===php_sapi_name() &&
__FILE__===realpath(
getcwd().DIRECTORY_SEPARATOR.$_SERVER['argv'][0]
)) {
// cli
define (NEW_LINE, "\n");
$iscli = 1;
} else {
define (NEW_LINE, "<br/>");
$iscli = 0;
}
if (!$iscli) {
show_source(__FILE__);
echo "</body></html>";
}