**************************************************************
object(Singleton)#1 (0) {
}
object(Singleton)#2 (0) {
}
object(Singleton)#2 (0) {
}
bool(false)
bool(false)
bool(true)
__CLASS__.self::$ncount;
Singleton2
__CLASS__.self::$ncount;
Singleton2
__CLASS__.self::$ncount;
Singleton2
unset
Singleton1
object(Singleton)#1 (0) {
}
**************************************************************
<?php
class Singleton
{
private static $instance;
// if max_instance is 1, we have a pure singleton
private static $ncount = 0;
const MAX_INSTANCE = 2;
private function __construct() {}
private function __clone() {}
public static function getInstance()
{
if (self::$ncount < self::MAX_INSTANCE) {
self::$instance = new Singleton;
++self::$ncount;
}
return self::$instance;
}
public function doAction()
{
echo __CLASS__.self::$ncount;
}
public function __destruct()
{
--self::$ncount;
}
}
//usage
//Singleton::getInstance()->doAction();
$first = Singleton::getInstance();
// object(Singleton)#1 (0) { }
$second = Singleton::getInstance();
// object(Singleton)#2 (0) { }
$third = Singleton::getInstance();
// object(Singleton)#2 (0) { }
echo "<pre>\n", str_repeat("*", 62), "\n";
var_dump($first);
var_dump($second);
var_dump($third);
var_dump($fist instanceof Singleton);
var_dump($first === $second); // false
var_dump($second === $third); // true
echo "\n\n__CLASS__.self::\$ncount;\n";
$first->doAction();
echo "\n\n__CLASS__.self::\$ncount;\n";
$second->doAction();
echo "\n\n__CLASS__.self::\$ncount;\n";
$third->doAction();
echo "\n\nunset\n";
unset($first, $second, $third);
$first = Singleton::getInstance();
$first->doAction();
echo "\n\n";
var_dump($first);
// object(Singleton)#1 (0) { }
echo str_repeat("*", 62)."</pre>";
if ('cli'===php_sapi_name() &&
__FILE__===realpath(
getcwd().DIRECTORY_SEPARATOR.$_SERVER['argv'][0]
)) {
// cli
define (NEW_LINE, "\n");
$is_cli = 1;
} else {
define (NEW_LINE, "<br/>");
$is_cli = 0;
}
if (!$is_cli) {
show_source(__FILE__);
echo "</body></html>";
}
?>