PHP Extends Class


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()是在我扩展的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);

中的大括号时,致命错误将消失

第一种方法很好,但是你需要记住你调用的是$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类的文件?

你必须require_once 'DB.php'