2015-09-05 248 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'; –