在php中:如何在同一个类中的函数之间传递$ conn(mysqli)对象?

时间:2018-01-18 17:16:54

标签: php mysqli

我确实有以下我正在编写的PHP代码:

public $conn;

public function start(){
    $this->conn = new mysqli($this->servername, $this->username, $this->password, $this->dbName);
    if ($this->conn->connect_error) {
        die("Connection failed: " . $this->conn->connect_error);
    }


}

public function sql($q){

    $res=  $this->conn->query($q);  
    echo $res;
    return $res;    
}

以下代码在创建db类的对象时使用时会出错。

如何正确地在函数start和函数sql之间传递$ conn对象?

由于

2 个答案:

答案 0 :(得分:1)

假设这是一个数据库连接包装器,我会将函数start更改为类构造函数:

class DbWrapper {
    public $conn;

    public function __construct(){
        $this->conn = new mysqli($this->servername, $this->username, $this->password, $this->dbName);
        if ($this->conn->connect_error) {
            die("Connection failed: " . $this->conn->connect_error);
        }
    }

    public function sql($q) {
        $res = $this->conn->query($q);  
        //echo $res; /* echo doesn't print object */
        return $res;    
    }
}

$db = new DbWrapper();
$db->sql('SELECT ...');

答案 1 :(得分:0)

当您致电sql()时,第一行应为start(),因为您需要先在$conn函数中初始化start()变量。现在在页面刷新时你会失去它,所以你应该从你的sql函数中调用它。

public function sql($q){
    $this->start();
    $res=  $this->conn->query($q);  
    echo $res;
    return $res;    
}

如果直接调用sql函数,则不会初始化$conn变量。