这是我连接到数据库的类,但当我创建该类的实例时,它给了我这个错误:Fatal error: Call to undefined method DB::query()
在C:'Apache24'htdocs'core'DB.class.php第21行。
<?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>';
?>
致命错误:调用未定义的方法DB::query()在C:'Apache24'htdocs'core'DB.class.php第21行
构造函数不返回自定义值,它们返回类的实例。为了测试这一点,使用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`");