在对象中存储mysqli连接

时间:2015-03-13 22:05:27

标签: php mysqli

我试图在一个类中包含我的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对象为null。

例如:

$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

1 个答案:

答案 0 :(得分:0)

当然$ sqlObj-> getConn()返回的null或false(或其他对象)不是所需的类型。 我建议你在getConn()中抛出一个新错误并用try / catch块换行。在这个throw中,返回来自getConn的错误,你将能够更好地理解它。顺便说一句,连接参数是否正常?这似乎与此有关。