这种模式确保一个类只有一个实例并提供一个访问它的全局访问点
Singleton
This class (a) defines an Instance operation that lets clients access its unique instance, and (b) may be responsible for creating its own unique instance.
(这类(a)定义了一个实例操作,允许客户访问其独特的实例,和(b)可能是负责创建自己唯一的实例。)
<?php
class Singleton
{
static private $_instance = null;
private function __construct() {
}
static public function getInstance() {
if (is_null(self::$_instance)) {
self::$_instance = new Singleton();
}
return self::$_instance;
}
/**
* 防止用户克隆实例
*/
public function __clone() {
die('Clone is not allowed.' . E_USER_ERROR);
}
public function display() {
echo "it is a singlton class function";
}
}
$obj = Singleton::getInstance();
var_dump($obj);
$obj->display();
$obj1 = Singleton::getInstance();
var_dump(($obj === $obj1));
评论