首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP扩展类

PHP扩展类
EN

Stack Overflow用户
提问于 2015-09-05 12:26:55
回答 2查看 79关注 0票数 1

大家早上好。我编写了一个返回我的类:

代码语言:javascript
复制
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文件的第一部分:

代码语言:javascript
复制
session_start();
$_SESSION['ID'] = 1;
require_once 'pass/password.inc.php'; /*Here's the DB Class*/

我将一个类扩展到另一个类,下面是代码:

代码语言:javascript
复制
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类没有初始化,当我初始化时,错误是相同的,这是我所做的:

代码语言:javascript
复制
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);中的大括号时,致命错误将消失。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-09-05 12:35:07

第一种方法很好,但是您需要记住,您正在调用$db->row(,因为它存在于父类中,因此需要对其使用$this->

代码语言:javascript
复制
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获得它,如下所示:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2015-09-05 12:33:29

你必须require_once 'DB.php‘

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32413036

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档