2015-09-05 131 views
1

Goodmorning everyone。 我编写返回我的类:PHP扩展类

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);

回答

0

第一种方式是不错,但你要记住,因为它在你需要使用就可以了$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()); 
01父类存在您所呼叫

而且保持类的封装好的和紧张,这将是更好的会话传递给构造函数,而不是从$ _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类的文件?

+0

是的,像这样: <?php session_start(); $ _SESSION ['ID'] = 1; require_once'pass/password.inc.php'; require_once'pass/password.inc.php'; –

+0

public function pgname($ id){ $ rs = $ this-> db-> row(“SELECT CONCAT(Nome,',Cognome)FROM Personaggio WHERE ID =:id”,array(“id”=> $ ID)); return($ rs); } $ pg = new pg(); echo($ pg-> pgname($ _ SESSION ['ID'])); 仍然不工作,这是输出: 注意:未定义的属性:pg :: $ db在/ Applications/MAMP/htdocs /测试版第9行上的Vari/index.php 致命错误:致电成员函数row()on null在/ Applications/MAMP/htdocs/Test Vari/index.php on line 9 –

+0

阅读我的回答'$ rs = $ this-> row(“....'not'$ this-> db - > row('你不需要'db',因为你已经扩展了DB类,所有的类都被看作是一个单独的实体 – RiggsFolly

0

删除括号中的致命错误会消失,你有require_once“db.php中”

+0

我忘了说,但它在这里: <?php session_start(); $ _SESSION ['ID'] = 1; require_once'pass/password.inc.php'; require_once'pass/password.inc.php'; –