Php 在对象中存储mysqli连接

Php 在对象中存储mysqli连接,php,mysqli,Php,Mysqli,我试图将我的mysqli对象包含在一个类中,其他对象/脚本可以使用。我这样初始化它: $this->host = $Host; $this->username = $UName; $this->password = $PWord; $this->database = $DBName; $this->debugEmail = $debugEmail; // Creat

我试图将我的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的错误,您将能够更好地理解它。顺便问一下,连接参数是否正常?这似乎与此有关

你应该发布你的类定义,一些细节在你的问题中不清楚。例如:getConn是如何定义的?我们猜不到这一点。还有一点需要注意:对于这样的类或对象,sqlObject并不是一个好名字。此类的对象不是sql,是吗?这是一个数据库连接。所以就这样称呼它,这样你的代码就更容易理解了。它似乎认为错误消息很少是错误的。这意味着您的对象在从其他地方调用时构造不正确。您是否在工作示例中使用getConn?可能函数实际上没有返回连接?我已经在sqlObject.php文件中将$conn变量从内部私有变量更改为全局变量,这就解决了这个问题。这对我来说意味着:$This->conn=newmysqli这一行在init函数的末尾超出了范围。