1.构造函数的私有化
2.定义一个私有的静态的属性
3.定义一个静态的获取单例的方法
class myDbTool{
private static $instance;//定义私有静态的属性用以存储单例对象
//定义单例对象的静态方法
static function getInstance($config){
if(!isset(self::$instance)){
self::$instance=new self($config);}
return self::$instance;
}
//做数据库连接
private function __construct($config){
//将这些基本的链接信息保存起来
$this->host=!empty($config['host'])?$config['host']:'localhost';
$this->port=!empty($config['port'])?$config['port']:'3306';
$this->user=!empty($config['user'])?$config['user']:'root';
$this->pass=!empty($config['pass'])?$config['pass']:'123';
$this->charset=!empty($config['charset'])?$config['charset']:'utf8';
$this->dbname=!empty($config['dbname'])?$config['dbname']:'yurongfu';
//连接数据库
$this->link=@mysql_connect("{$this->host}:{$this->port}","{$this->user}","{$this->pass}")or die("连接失败");
//设定编码
$this->setCharset($this->charset);
//设定使用的数据库
$this->setDB($this->dbname);
}}
最后要获得实例写法
$db=myDbTool::getInstance($config);