当试图返回数据库对象$conn时,我一直得到错误"未定义的变量:conn"answers"无法访问空属性"。但是,数据库连接正在工作。是否有更好的方法来返回一个数据库对象比$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;
}
一行:
$conn = mysqli_connect($host,$user,$password,$database);
应:$this->conn = mysqli_connect($host,$user,$password,$database);
你应该删除这一行:
return $this->$conn;
首先,构造函数不应该返回任何东西(PHP会自动返回新对象)。第二,应该是$this->conn
(conn
之前没有$
)。
最后一行:
$conn;
既错误又无用。把它删掉