我已经做了各种各样的事情来了解代码的实际错误,但我无法弄清楚是什么导致了这个错误。对null调用成员函数?
下面是类称为Topic
:
class Topic {
// Init DB variables
private $db;
/*
* Constructor
*/
public function __contruct() {
$this->db = new Database();
}
/*
* Get All Topics
*/
public function getAllTopics() {
$this->db->query("SELECT topics.*, users.username,
users.avatar, categories.name
FROM topics
INNER JOIN users
ON topics.user_id = users.id
INNER JOIN categories
ON topics.category_id = categories.id
ORDER BY create_date DESC");
// Assign the results
$results = $this->db->resultset();
return $results;
}
}
当我创建Topic
类的一个对象,
$topic = new Topic();
$results = $topic->getAllTopics();
总是有这样的错误:
致命错误:调用成员函数query()o ñ空在 /Applications/XAMPP/xamppfiles/htdocs/forumproject/libraries/Topic.php 上线25即$这个 - > DB->查询(...)
的Database
类是可以正常使用因为我已经为该课程独立运行测试,并且没有问题。
这里是数据库类:
<?php
/*
* Using PDO for the first time in my life.
*/
class Database {
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
private $dbh;
private $error;
private $stmt;
public function __construct() {
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instance
try {
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
// Catch the errors using exceptions handler
catch(PDOException $e){
$this->error = $e->getMessage();
}
}
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
public function bind($param, $value, $type = null){
if(isnull($type)){
switch(true){
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default :
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function execute(){
return $this->stmt->execute();
}
public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_OBJ);
}
public function single(){
$this->execute();
return $this->stmt->fetch(PDO::FETCH_OBJ);
}
public function rowCount(){
return $this->stmt->rowCount();
}
public function lastInsertId(){
return $this->dbh->lastInsertId();
}
public function beginTransaction(){
return $this->dbh->beginTransaction();
}
public function endTransaction(){
return $this->bbh->commit();
}
public function cancelTransaction(){
return $this->dbh->rollBack();
}
}
?>
数据库类是否在同一个文件中?如果不是,你必须“包含”/“要求”它。 –
这是你完整的主题文件吗?致命错误建议在第25行,在第19行上调用查询函数。 –
@TomUdding是,我包含它。 – manjula