我目前正在尝试传递数据库连接,如下所示:
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()。我做错了什么?
答案 0 :(得分:1)
你的传递db-to-class-constructor部分是正确的。
但这不是一个有效的类定义,就像你编码它一样。您需要将这些代码行(// execute some query
之后)放入函数中。代码行不能存在于它们所在的位置,在User类内部浮动但不在函数内部。这不是合法的PHP。
每次调用prepare()或execute()后,还应检查错误状态。如果出现错误,如SQL语法错误或表不存在等,则返回FALSE。
class User {
public $db;
function __construct($db) {
if (! $db instanceof PDO) { die("What are you trying to pull anyway?"); }
$this->db = $db;
}
function doSomething() {
// execute some query
$sql = "SELECT * FROM test";
$sth = $this->db->prepare($sql);
if ($sth === false) {
die(print_r($this->db->errorInfo(), true));
}
$status = $sth->execute();
if ($status === false) {
die(print_r($sth->errorInfo(), true));
}
$result = $sth->fetch();
if(!empty($result)) {
echo '<pre>';
var_dump($result);
echo '</pre>';
}
}
}