单例模式时一个类只能有一个实例,并且类内部自行实例化,且对外提供获得实例的方法
一个最简单的php单例模式代码
<?php
class Singleton
{
private static $instance;
private function __construct()
{
}
public static function getInstance()
{
if (empty(self::$instance)){
self::$instance = new Singleton();
}
return self::$instance;
}
}
测试重复获得实例
<?php
$singleton1 = Singleton::getInstance();
$singleton2 = Singleton::getInstance();
var_dump($singleton1);
var_dump($singleton2);
输出
object(Singleton)#1 (0) {
}
object(Singleton)#1 (0) {
}
以上输出中,对象的id都是#1,说明重复获得的实例其实是同一个。
通过设置属性,继续测试
<?php
class Singleton
{
private static $instance;
private $name;
private function __construct()
{
}
public static function getInstance()
{
if (empty(self::$instance)){
self::$instance = new Singleton();
}
return self::$instance;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
执行
<?php
$singleton1 = Singleton::getInstance();
$singleton2 = Singleton::getInstance();
$singleton1->setName('aaa');
$singleton2->setName('bbb');
echo $singleton1->getName();
echo "\n";
echo $singleton2->getName();
输出
bbb
bbb
通过进一步测试,说明重复获得的实例其实是同一个。单例模式通常用于获得数据库连接,因为程序一次执行过程中可能需要操作多次数据库,使用单例模式避免多次new创建实例浪费数据库连接资源。