我目前正在尝试按如下方式传递数据库连接:
class Test {
public $user;
public $db;
function __construct() {
// connect to database
try {
$this->db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_DATABASE.'', DB_USERNAME, DB_PASSWORD);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $err) {
die($err->getMessage());
}
$this->user = new User($this->db);
}
}
class User {
public $db;
function __construct($db) {
$this->db = $db;
}
// execute some query
$sql = "SELECT * FROM test";
$sth = $this->db->prepare($sql);
$sth->execute();
$result = $sth->fetch();
if(!empty($result)) {
echo '<pre>';
var_dump($result);
echo '</pre>';
}
}
但我得到:致命错误:在非对象上调用成员函数 prepare()。我究竟做错了什么?