【发布时间】:2014-03-08 13:35:18
【问题描述】:
我在我的 PHP 项目中使用单例数据库连接类连接到 MySql 数据库。
// the singleton method
public static function getDatabaseConnection()
{
if (self::$databaseConnection == null)
{
self::$databaseConnection = new DatabaseConnection();
self::$databaseConnection->connect();
}
return self::$databaseConnection;
}
private function connect()
{
$this->connection = new mysqli($this->hostName, $this->username, $this->password, $this->databaseName)
or die (mysqli_connect_error());
}
// When should I call this method?!
public function close_connection() {
if (isset($this->connection)) {
$this->connection->close();
}
}
在初始化单例对象时,它将连接到数据库。
我只是不知道什么时候应该关闭这个连接?不关闭就保存了吗?
任何额外的提示将非常感激,谢谢。
【问题讨论】:
-
PHP 将在脚本终止时关闭它。你真的不需要手动关闭它。如果您有理由想要重新建立它,您可以关闭并重新打开它。
-
注意:当您连接到
mysqli时,我在那里看到mysql_error()。这 2 个 API不兼容。你应该检查mysqli_connect_error()us3.php.net/mysqli_connect_error -
已编辑,感谢您的关注。 :)
标签: php mysql database-connection