我确实有以下我正在编写的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对象?
由于
答案 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
变量。