PHP在扩展类中自动调用方法

时间:2014-05-11 15:29:20

标签: php class

我不知道是否有类似的东西,但我搜索了超过5个小时但没有出现正面结果。

我有一个名为DataBase的类,它有一个名为connect的函数,它连接到数据库

我要做的是自动调用方法“connect”而不是每次在我的扩展类中调用它

但它无法正常工作,

我真正做了什么,我在我的扩展课程中调用了connect函数,但它告诉我没有选择数据库

这是一个例子

我的数据库php文件

include_once "config.php";
class DataBase {
  private $_localhost;
  private $_user;
  private $_password;
  private $_dbname;
  protected $db;

  function __construct($localhost,$user,$password,$dbname){

    $this->_localhost = $localhost;
    $this->_user      = $user;
    $this->_password  = $password;
    $this->_dbname    = $dbname;
    $this->connect();
 }

 function connect(){
   try{
    $this->db = new PDO("mysql:host=".$this->_localhost.";dbname=".$this->_dbname,$this->_user,$this->_password);
    $this->db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

    }catch(PDOException $e){
      echo $e->getMessage();
    }

  }

  function close(){
    $this->db = null;
  }

}

$db = new DataBase($localhost,$user,$password,$dbname);

我的查询php文件

class display extends DataBase{
  private $tbname;
  private $sql;
  private $query;
  private $show_data;

  function __construct($tbname){

    $this->tbname = $tbname;
    parent::connect();

  }
  function getLastRow(){

      $this->sql = "SELECT * FROM ".$this->tbname." ORDER BY id DESC LIMIT 1";

      $this->query = $this->db->prepare($this->sql);

      try{
         $this->query->execute();
       }catch(PDOException $e){
         echo $e->getMessage();
      }    
      $this->show_data = $this->query->fetch();

      if($this->show_data){
      return $this->show_data;
      }

  }
}

现在当我尝试在我的任何控制器文件中进行新显示时,它会给我这个错误

  

SQLSTATE [3D000]:无效的目录名称:1046未选择数据库

正如我所说,我想要做的是在我的扩展类中使用此属性$ this-> db并自动调用“connect”函数或类似于tihs

1 个答案:

答案 0 :(得分:1)

您如何想象DataBase类将接收有关数据库,用户,密码和主机的信息?

需要在子类的构造函数中接收该信息,然后使用这些参数调用parent::__construct()

除了你喜欢反模式和糟糕的设计外,别无他法。

在你的孩子班上:

function __construct($localhost, $user, $password, $dbname, $tbname){
    $this->tbname = $tbname;
    parent::__construct($localhost, $user, $password, $dbname);
}

实际上,最好只将DataBase实例注入到显示类中,而不是在这里使用继承。您可能希望多次重复使用相同的连接。

function __construct(DataBase $db, $tbname){
    $this->tbname = $tbname;
    $this->database = $db;
}
// you can now install some __call() wrapper in your DataBase class to proxy calls to $db property 

并在您的主要代码中

$db = new DataBase($localhost, $user, $password, $dbname);
$display = new display($db, $table);
// now you can reuse $db for other classes/direct use.