单例模式顾名思义,就是只有一个实例。由此借鉴之,在数据库操作中,对于同一个库只允许一个实例存在很重要.
<?php
class mysql
{
protected $db;
static private $instance = null;
/**
* 得到数据库连接
*
*/
private function getDb()
{
//已有连接
if(isset(self::$instance))
{
$this->db = self::$instance;
}
else
{
//无此连接
global $__db__;
extract($__db__);
$dsn = "mysql:host=$host;port=$port;dbname=$database";
try {
$this->db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
self::$instance = $this->db;
}
}
/**
* 运行sql
*
* @param sql $sql
*/
private function query($sql)
{
$this->getDb();
......
}
}
?>
class mysql
{
protected $db;
static private $instance = null;
/**
* 得到数据库连接
*
*/
private function getDb()
{
//已有连接
if(isset(self::$instance))
{
$this->db = self::$instance;
}
else
{
//无此连接
global $__db__;
extract($__db__);
$dsn = "mysql:host=$host;port=$port;dbname=$database";
try {
$this->db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
self::$instance = $this->db;
}
}
/**
* 运行sql
*
* @param sql $sql
*/
private function query($sql)
{
$this->getDb();
......
}
}
?>