单例模式
示例:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36class Preferences
{
private $props = array();
private static $instance;
private function __construct()
{
}
public static function getInstance()
{
if (empty(self::$instance)) {
self::$instance = new Preferences();
}
return self::$instance;
}
public function setProperty($key, $val)
{
$this->props[$key] = $val;
}
public function getProperty($key)
{
return $this->props[$key];
}
}
$pref = Preferences::getInstance();
$pref->setProperty('name', 'wang');
unset($pref); // 解除引用
$pref2 = Preferences::getInstance();
echo $pref2->getProperty('name');
// 输出: wang