我是 PHP
的新手,我正在尝试执行这个简单的任务:从 MySql
数据库获取数据。
我创建了一个单例类来与数据库通信:
class Database {
private static $db = null;
private $servername;
private $username;
private $password;
private $connection;
private function Database(){
$this->servername = "localhost";
$this->username = "user";
$this->password = "123456";
}
public static function get_database(){
if(!static::$db){
static::$db = new Database();
}
return static::$db;
}
function start_connection(){
$this->connection = new mysqli($this->servername,
$this->username,
$this->password);
}
function execute_query($query){
$this->start_connection();
[...]
$this->disconnect();
}
function disconnect(){
$this->connection->close();
}
[...]
}
这段代码工作得很好,但有一件事困扰着我。我想知道每次调用 start_connection()
时是否真的需要创建一个新的连接对象 new mysqli()
。有类似重新连接
之类的东西吗?
最佳答案
您可以在数据库类中存储 mysqli 实例,并在“私有(private)函数数据库”函数中声明它(如果您愿意,可以通过调用 $this->start_connection() 来声明)
如果您愿意,您也可以提供一个静态函数来关闭连接。
关于php - 每次我需要一些东西时创建新的mysql连接对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31343325/