我正在尝试将我的mysqli对象包含在其他对象/脚本可以使用的类中。我像这样初始化它:
$this->host = $Host;
$this->username = $UName;
$this->password = $PWord;
$this->database = $DBName;
$this->debugEmail = $debugEmail;
// Create sql handler
$this->conn = new mysqli($this->host, $this->username, $this->password, $this->database);
// Check connection
if ($this->conn->connect_error) {
die("Connection Failed: " . $this->conn->connect_error());
}
问题是当我在其他地方使用此对象时,它似乎认为 conn 对象为空。
例如:
$sqlObj = new sqlObject();
$sqlObj->init();
// run query
$sql = "SELECT * FROM table";
$result = $sqlObj->getConn()->query($sql);
它返回:
Call to a member function query() on a non-object
当然,
$sqlObj->getConn() 返回的 null 或 false(或其他对象)不是所需的类型。我建议你在 getConn() 中抛出一个新错误,并使用 try/catch 块包装。在此抛出中,返回来自getConn的错误,您将能够更好地理解它。顺便说一句,连接参数可以吗?这似乎与此有关。