0
連接我有一個單獨的數據庫連接類 - db.php中(通過在google找到):如何關閉從擴展的類
<?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)中的連接?
關於你的回答,提出了一個相關的問題,如果我從其他類擴展db類(例如將有兩個類將擴展db類),會有兩個連接還是隻有一個? –
@ AbdullahMamun-Ur-Rashid您已經將'db'類實現爲Singleton模式,因此將只有一個**類的實例**,它將在另外兩個類之間共享。所以沒有問題。一個小問題是,不是在'ext'類的'connect()'方法中創建和分配父實例,而是在構造方法中也可以這樣做。這沒有什麼區別。 –
非常感謝 –