[英]PHP Extends Class
大家,早安。 我编写了一个返回我的类:
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()是在我扩展的数据库类中声明的,并且我肯定可以正常工作。 数据库类未初始化,当我这样做时,错误是相同的,这就是我的方法:
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);
括号时,致命错误将消失print_r($pg->pgname);
您必须require_once'DB.php'
第一种方法很好,但是您需要记住,您正在调用$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
类的文件?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.