【发布时间】:2016-12-24 16:59:21
【问题描述】:
我有一个单例数据库连接类-db.php(通过谷歌搜索找到):
<?php
/*
* Mysql database class - only one connection alowed
*/
class db {
private $_connection;
private static $_instance; //The single instance
private $_host = "localhost";
private $_username = "user_name";
private $_password = "password";
private $_database = "database";
/*
Get an instance of the Database
@return Instance
*/
public static function getInstance() {
if(!self::$_instance) { // If no instance then make one
self::$_instance = new self();
}
return self::$_instance;
}
// Constructor
private function __construct() {
$this->_connection = new mysqli($this->_host, $this->_username,
$this->_password, $this->_database);
// Error handling
if(mysqli_connect_error()) {
trigger_error("Failed to conencto to MySQL: " . mysql_connect_error(),
E_USER_ERROR);
}
// Magic method clone is empty to prevent duplication of connection
private function __clone() { }
// Get mysqli connection
public function getConnection() {
return $this->_connection;
}
public function closeConnection(){
$this->_connection->close();
}
}
?>
为了测试连通性,如果我像这样在 ext.php 中扩展该数据库类:
<?php
class ext extends db {
private $conn;
function __construct(){
$this->connect();
if(isset($this->conn)){
echo 'Connection is established<br />';
}
$this->closeConn();
}
public function connect(){
$this->conn = parent::getInstance()->getConnection();
}
public function closeConn(){
parent::closeConnection();
}
}
?>
在我的 index.php 页面中:
<?php
spl_autoload_register(function ($class) {
include '../classes/' . $class . '.php';
});
$test = new ext();
?>
现在我的输出如下:
Connection is established
Fatal error: Call to a member function close() on a non-object in (line number) of db.php
我的问题是如何关闭扩展类 (ext.php) 中的连接?
【问题讨论】: