1 <?php
2 /**
3 *单件模式
4 */
5 class Singleton {
6 private static $instance = null;
7 private $_field = null;
8
9 public static function getInstance(){
10 if(self::$instance == null)
11 self::$instance = new self();
12 return self::$instance;
13 }
14
15 /**
16 *私有化构造函数和对象复制
17 */
18 private function __clone(){}
19 private function __construct(){}
20 private function Singleton(){}
21
22 /**
23 *成员函数
24 */
25 public function setField($field){
26 $this->field = $field;
27 }
28 public function getField(){
29 return $this->field;
30 }
31 }
32
33 /**
34 *test
35 */
36
37 $obj_1 = Singleton::getInstance();
38 $obj_2 = Singleton::getInstance();
39
40 $obj_1->setField('hello');
41 echo $obj_2->getField();
42
43 echo "<br/>";
44 $obj_2->setField('world');
45 echo $obj_1->getField();
46 ?>
输出:
hello
world
浙公网安备 33010602011771号