PHP扩展了类

时间:2015-09-05 12:26:55

标签: php class

Goodmorning everyone。 我编写了一个回复我的课程:

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

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

2 个答案:

答案 0 :(得分:0)

你需要require_once'DB.php'

答案 1 :(得分:0)

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