PHP单例模式

Author Avatar
在路上 2月 01, 2012

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
36
37
class SingletonClass {
// singleton instance
private static $instance;
//private constructor function
//to prevent external instantiation
private function __construct(){}
//getInstance method
public static function getInstance() {
if(!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public function run() {
print "run...\n";
}
}
$className = "SingletonClass";
$instance = SingletonClass::getInstance();
$instance = $className::GetInstance();
$instance = $className::getInstance();
//都可以执行成功,php类的方法名难道不区分大小写。
$instance = SingletonClass::getInstance();
$instance->run();
//js里有eval,php里也有,都可以执行代码
eval('$instance1 = '.$className.'::GetInstance();');
$instance1->run();

2017-08-27 整理