单例模式: 一个类生成一个且只有一个对象实例。
代码如下:
class db {
private static $db_instance;
/*设置构造函数为私有函数*/
private function __construct(){
}
public static function getInstance(){
if (empty(self::$db_instance))
self::$db_instance = new db();
return self::$db_instance;
}
...
}
如上述代码所示,实现单例模式主要做如下工作:
1. 设置构造函数为私有函数,不能通过new 关键字来实例化类;
2. 设置db_instance 为private 且 static ,外部不能访问;
3. 设置一个可以访问db_instance的方法,设置为public 且static;