大家早上好。我编写了一个返回我的类:
Notice: Undefined variable: db in /Applications/MAMP/htdocs/Test Vari/index.php on line 12
Fatal error: Call to a member function row() on null in /Applications/MAMP/htdocs/Test Vari/index.php on line 12这是php文件的第一部分:
session_start();
$_SESSION['ID'] = 1;
require_once 'pass/password.inc.php'; /*Here's the DB Class*/我将一个类扩展到另一个类,下面是代码:
class pg extends DB{
public $id;
function __construct(){
parent::__construct();
$this->id = $_SESSION['ID'];
}
public function pgname(){
$rs = $db->row("SELECT CONCAT(Nome, ' ', Cognome) FROM Personaggio WHERE id = :id",array("id"=>$this->id));
return($rs);
}
}
$pg = new pg();
print_r ( $pg->pgname());$ DB ->row()是在我扩展的DB类中声明的,我确信这是可行的。DB类没有初始化,当我初始化时,错误是相同的,这是我所做的:
class pg extends DB{
public $id;
public $db;
function __construct(){
parent::__construct();
$this->db = new DB();
$this->id = $_SESSION['ID'];
}
public function pgname(){
$rs = $db->row("SELECT CONCAT(Nome, ' ', Cognome) FROM Personaggio WHERE id = :id",array("id"=>$this->id));
return($rs);
}
}删除print_r($pg->pgname);中的大括号时,致命错误将消失。
发布于 2015-09-05 12:35:07
第一种方法很好,但是您需要记住,您正在调用$db->row(,因为它存在于父类中,因此需要对其使用$this->
class pg extends DB{
public $id;
function __construct(){
parent::__construct();
$this->id = $_SESSION['ID'];
}
public function pgname(){
$rs = $this->row("SELECT CONCAT(Nome, ' ', Cognome) FROM Personaggio WHERE id = :id",array("id"=>$this->id));
return($rs);
}
}
$pg = new pg();
print_r ( $pg->pgname());此外,为了保持类的封装良好和紧凑,最好将会话传递给构造函数,而不是从构造函数中的$_SESSION获得它,如下所示:
class pg extends DB{
public $id;
function __construct($id){
parent::__construct();
$this->id = $id;
}
public function pgname(){
$rs = $this->row("SELECT CONCAT(Nome, ' ', Cognome) FROM Personaggio WHERE id = :id",array("id"=>$this->id));
return($rs);
}
}
$pg = new pg($_SESSION['ID']);
print_r ( $pg->pgname());我还假设您包含了包含DB类的文件?
发布于 2015-09-05 12:33:29
你必须require_once 'DB.php‘
https://stackoverflow.com/questions/32413036
复制相似问题