单利模式的核心点在于只能生成1个对象,并且是由类中的静态变量保存。
以下代码来自《深入PHP 面向对象、模式与实践》(第三版)第9章
/**
* Created by PhpStorm.
* User: Eilen
* Date: 2018/8/31
* Time: 22:48
*/
class Preferences
{
private $props = array();
private static $instance;
private function __construct(){}
/**
* 获取单例模式对象
* @return mixed
*/
public static function getInstance()
{
if (empty(self::$instance)){
self::$instance = new Preferences();
}
return self::$instance;
}
/**
* 接收对象的参数,并且赋值
* @param $key
* @param $val
*/
public function setProperty($key, $val)
{
$this->props[$key] = $val;
}
public function getProperty($key)
{
return $this->props[$key];
}
}
//引用单例模式
$pref = Preferences::getInstance();
$pref->setProperty('name', 'matt');
unset($pref);
$pref2 = Preferences::getInstance();
print $pref2->getProperty('name');