是的,这是可能的.我建议使用一个启动
MySQL连接的构造函数和一个使它无效的析构函数.这样,每次要打开和关闭连接时,都不必手动调用该函数.每当调用该对象的新实例时,该连接将打开,并且当没有对该对象的进一步引用时,该连接将被取消.
它可能看起来像这样:
private $l; //MySQL Connection
//Called automatically upon initiation
function __construct() {
try {
$this->l = new PDO("mysql:host=".MYSQL_HOST.";dbname=".MYSQL_DATABASE, MYSQL_USER, MYSQL_PASSWORD); //Initiates connection
$this->l->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); // Sets error mode
} catch (PDOException $e) {
file_put_contents("log/dberror.log", "Date: " . date('M j Y - G:i:s') . " ---- Error: " . $e->getMessage().PHP_EOL, FILE_APPEND);
die($e->getMessage()); // Log and display error in the event that there is an issue connecting
}
}
//Called automatically when there are no further references to object
function __destruct() {
try {
$this->l = null; //Closes connection
} catch (PDOException $e) {
file_put_contents("log/dberror.log", "Date: " . date('M j Y - G:i:s') . " ---- Error: " . $e->getMessage().PHP_EOL, FILE_APPEND);
die($e->getMessage());
}
}