在尝试返回数据库对象$ conn时,我不断收到错误“Undefined variable:conn”和“无法访问空属性”。但是,数据库连接正在运行。是否有更好的方法来返回数据库对象而不是$ this-> $ conn;?
class database {
private $host = "xxxx";
private $database = "xxxx";
private $user = "xxxx";
private $password = "xxxx";
public $conn = "";
function db_connect() {
try {
$conn = mysqli_connect($host,$user,$password,$database);
$conn;
echo "Connected to database";
echo "<br>";
return $conn;
}
catch(PDOException $e)
{
echo 'Connection Failed:';
echo "<br>";
echo $e->getMessage();
}
}
public function __construct(){
$this->db_connect();
return $this->$conn;
}
答案 0 :(得分:0)
该行:
$conn = mysqli_connect($host,$user,$password,$database);
应该是:
$this->conn = mysqli_connect($host,$user,$password,$database);
您应该删除该行:
return $this->$conn;
首先,构造函数不应返回任何内容(PHP会自动返回新对象)。其次,它应该是$this->conn
(在$
之前没有conn
。)
最后,行:
$conn;
既错也没用。摆脱它。