单例模式指的是在应用程序的范围内只对指定的类创建一个实例。
单例模式包含的对象只有一个,就是单例本身。
使用单例模式的类通常拥有一个私有构造函数和一个公有克隆函数,确保用户无法通过创建对象或克隆的方式对其进行实例化。
除些之外,该模式中还包含一个静态私有成员变量 $instance 与静态方法 getInstance。
getInstance 方法负责对其本身实例化,然后将这个对象存储在 $instance 静态成员变量中,以确保只有一个实例被创建。
<?php
/**
* SingelTon 单例模式
* LSB 延迟静态绑定
*/
class Singleton
{
protected static $_instance = null;
private function __construct()
{
}
public function __clone()
{
trigger_error("Clone is not allowed, ", E_USER_ERROR);
}
public static function getInstance()
{
if (null !== static::$_instance) {
return static::$_instance;
}
static::$_instance = new static;
return static::$_instance;
}
}
/**
* MYSQL实例
*/
class Mysql extends Singleton
{
protected static $_instance = 'Mysql';
}
/**
* MSSQL实例
*/
class Mssql extends Singleton
{
protected static $_instance = 'Mssql';
}
var_dump(Singleton::getInstance());
var_dump(Mysql::getInstance());
var_dump(Mssql::getInstance());
class Cache
{
private static $instance = null;
private function __construct()
{
}
public static function getInstance()
{
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public function __clone()
{
trigger_error("Clone is not allowed, ", E_USER_ERROR);
}
}
$cache = Cache::getInstance();
$cache2 = clone $cache;
var_dump($cache);
var_dump($cache2);
object(Singleton)#1 (0) {
}
string(5) "Mysql"
string(5) "Mssql"
<br />
<b>Fatal error</b>: Clone is not allowed, in <b>D:\www\demo\phper\Singleton.php</b> on line <b>71</b><br />