我写了一个聊天模块,在这个模块中用于降低数据库的压力我使用单例设计模式来获取pdo Object.this是我的驱动程序类使用单音模式:
class driver {
protected $_servername= "localhost";
protected $_username= "****";
protected $_password= "****";
protected $_dbname= "***";
private static $instance;
private $dbConn;
// The db connection is established in the private constructor.
public function __construct()
{
$this->dbConn = new PDO("mysql:host=$this->_servername;dbname=$this->_dbname", $this->_username, $this->_password);
// set the PDO error mode to exception
$this->dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public static function getInstance()
{
if(!self::$instance)
{
self::$instance = new driver();
}
return self::$instance;
}
public function getConnection()
{
return $this->dbConn;
}
public function __clone() {
throw new Exception("Can't clone a singleton");
}
}
在构造函数的chat类中我使用这个codde来获取实例:
$instance = driver::getInstance();
$conn = $instance->getConnection();
$this->_conn =$conn;
所以如果我输入像
这样的代码echo 123;die();
这样的getinstance
静态方法:
if(!self::$instance)
{
self::$instance = new driver();
echo 1111;die();
}
它总是返回1111.为什么静态$ instance变量没有被填充或者保持被驱动程序对象填充?