如何单例模式链接数据库
===================
1.单例模式
单例模式主要是三点:隐藏掉(private)自身的构造函数;提供一个获取静态实例的函数;类内维持一个静态的实例。
2.php如何连接数据库
如何安装数据库可以查看以下文章:
或者使用mamp,软件里面集成了Apache,MySQL,PHP。
使用mamp作为环境的参考php文件:
<?php
class Db{
private $_dbConfig = array(
'host' => '127.0.0.1',
'port' => '8889',
'user' => 'root',
'password' => 'root',
'database' => 'db',
'socket' => 'localhost:/Applications/MAMP/tmp/mysql/mysql.sock',
);
static private $_instance;
static private $_connectSource;
private function __construct() {}
static public function getInstance() {
if(!(self::$_instance instanceof self)) {
self::$_instance = new self();
}
return self::$_instance;
}
public function connect() {
if(!(self::$_connectSource instanceof self)) {
self::$_connectSource = mysql_connect($this->_dbConfig['host'].":".$this->_dbConfig['port'], $this->_dbConfig['user'], $this->_dbConfig['password']);
if(!self::$_connectSource) {
die('mysql connect error' . mysql_error());
}
mysql_select_db($this->_dbConfig['database'], self::$_connectSource);
mysql_query("set names UTF8", self::$_connectSource);
}
return self::$_connectSource;
}
}