在一个类中,我有一个建立数据库连接的方法,还有3个不同的方法a
,b
,c
方法。检查mysql连接
每a
,b
,c
方法,需要一个数据库连接,所以我检查如果MySQL没有连接 - 连接现在,别的什么也不做。这是我的代码:
class myClass {
public $DBisConnected = false;
function db_connect() {
$this->db = new mysqli("localhost","user","pass","db_name") or die("no conn");
$this->DBisConnected = true;
}
function a() {
if(!$this->DBisConnected) {
$this->db_connect();
}
// here process for a
}
function b() {
if(!$this->DBisConnected) {
$this->db_connect();
}
// here process for b
}
function c() {
if(!$this->DBisConnected) {
$this->db_connect();
}
// here process for c
}
}
我的问题是:是否有方法检查数据库连接是否已经存在?如果是这样,我将如何在我的代码中使用它们?
在构造函数中声明连接,所以您不必一次又一次地调用它。 – Vamsi