单例模式的定义:保证一个类只有一个实例,并提供一个访问它的全局访问点。
PHP实现单例模式:
class Singleton
{
//创建静态私有的变量保存该类对象
static private $instance;
//防止使用new直接创建对象
private function __construct(){}
//防止使用clone克隆对象
private function __clone(){}
static public function getInstance()
{
//判断$instance是否是Singleton的对象,不是则创建
if (!self::$instance instanceof self) {
self::$instance = new self();
}
return self::$instance;
}
public function test()
{
echo "我是一个单例模式";
}
}
$sing = Singleton::getInstance();
$sing->test();
单例模式和使用静态变量实现单例的区别:
单例模式强制类只能创建一个对象,一般是安全或者统一界面展示的时候会用到,而静态变量实现单例主要是为了减少new操作,并不能阻止new和clone操作。
参考链接:https://www.cnblogs.com/sgm4231/p/9851725.html
https://www.cnblogs.com/shamohai/p/11158206.html