这是我连接数据库的类,但是当我创建该类的实例时,它给了我这个错误:第21行的C:\ Apache24 \ htdocs \ core \ DB.class.php中的Fatal error: Call to undefined method DB::query()
<?php
class DB {
protected $db_name = "data_db";
protected $db_user = "root";
protected $db_pass = "root";
protected $db_host = "localhost";
public function __construct() {
$db = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
if ($db->connect_errno) {
printf("Connection failed: %s\n", $db->connect_error);
exit();
} else
return $db;
}
}
$db = new DB();
$data_row = $db->query("SELECT * FROM `users`");
while($data = $data_row->fetch_assoc())
echo $data["first_name"] . '<br>';
?>
致命错误:在第21行的C:\ Apache24 \ htdocs \ core \ DB.class.php中调用未定义的方法DB :: query()
答案 0 :(得分:2)
构造函数不返回自定义值,它们返回类的实例。要测试此使用var_dump( $db );
,输出将为object(DB) ...
。将连接保存为对象的属性,如:
public function __construct() {
$this->mysqli = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
}
$db = new DB();
$data_row = $db->mysqli->query("SELECT * FROM `users`");