1 <?php
2 //单例模式
3 class Dbconn{
4 private static $_instance=null;
5 protected static $_counter=0;
6 protected $_db;
7 private function __construct(){
8 self::$_counter+=1;
9 }
10 public static function getInstance(){
11 if(!self::$_instance instanceof self){
12 self::$_instance=new self();
13 }
14 return self::$_instance;
15 }
16 public function connect(){
17 echo "connected:".(self::$_counter)."\n";
18 return $this->_db;
19 }
20 }
21 ////使用单例模式后不能直接new对象,必须调用getInstance获取
22 $conn1=Dbconn::getInstance();
23 $_db=$conn1->connect();
24 //第二次调用是同一个实例,_counter还是1
25 $conn2=Dbconn::getInstance();
26 $_db=$conn2->connect();
27 ?>
28 结果显示:connected:1 connected:1