簡體   English   中英

PHP擴展類

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM