对于从PHP到MSSQL的数据库连接,我创建了以下代码。有人可以建议我,我的代码中的__destruct()函数是否自动工作并关闭数据库连接?这是我的代码:
<?php
class db{
private $connection;
private $server, $username, $password, $database, $charset;
public function __construct($server, $username, $password, $database, $charset){
$this->server = $server;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->charset = $charset;
$connectionInfo = array('UID'=>$this->username,
'PWD'=>$this->password,
'Database'=>$this->database,
'CharacterSet'=>$this->charset);
$this->connection = sqlsrv_connect($this->server, $connectionInfo);
if ($this->connection === false){
echo '<h2>Unable to connect to database</h2><br/>';
die (print_r(sqlsrv_errors(), true));
};
}
public function __destruct(){
sqlsrv_close($this->connection);
}
public function query($query, $params=null){
$result = sqlsrv_query($this->connection, $query, $params);
if (!$result){
echo 'Error in statement execution.\n';
die(print_r(sqlsrv_errors(), true));
}
return $result;
}
}
答案 0 :(得分:1)
除非未调用__destruct
方法,否则您的连接将被关闭。以下方案导致__destruct
无法执行:
- 如果在另一个析构函数中调用“exit”
- 取决于PHP版本:如果在“register_shutdown_function”函数中调用“exit”
- 如果代码中某处存在致命错误
- 如果在另一个析构函数中抛出异常
- 如果您尝试在析构函数中处理异常(PHP&gt; = 5.3.0)