在另一个类中打开连接类(PHP)

时间:2011-06-27 14:31:12

标签: php class

我有两个班级:

SQL连接类

   class MysqlDB {

   protected $_mysql;
   protected $_where = array();
   protected $_query;
   protected $_paramTypeList;

public function __construct($host, $username, $password, $db) {
      $this->_mysql = new mysqli($host, $username, $password, $db) or die('There was a problem connecting to the database');
   }

   public function query($query) 
   {
    //...................... }

   public function __destruct() {
        $this->_mysql->close();
   }
}

用户类

class cUser {

    private $_name;
    private $_email;
    private $_password;

    public function __construct() {
        $this->_name = '';
        $this->_email = '';
        $this->_password = '';
    }

    public function getUser($username) {
        global $db;
        return $db->query("SELECT * FROM user where username='$username'");
    }


}


**index.php**
<?php
require_once('cMysqlDB.php');
require_once('cUser.php');

$db = new MysqlDB('host','username','password','db');
$user = new cUser();
$userData = $user->getUser('username');
print_r($userData);
?>

完全有效!感谢Sabeen Malik

1 个答案:

答案 0 :(得分:0)

虽然我不完全确定你为什么要继承Users课程中的MySQL。但无论如何,如果你真的需要这样做的话。

而不是

$this->_conn = new MysqlDB($host, $username, $password, $db);

做的:

parent::__construct($host, $username, $password, $db);

您不需要$this->_conn只需使用$this->_mysql

我相信MysqlDB类将采用单例模式。 User类只需使用MySQLDB类的方法,例如:

$results = MySQLDB::instance()->query(whatever);

或那些线上的东西。有些人甚至使用全局$db对象并在他们的类中使用它(虽然我并不宽容),但有几种方法可以解决这个问题。我不确定你是否选择了正确的。

编辑: 使用全局$ db,您可以获得如下用户数据:

class cUser {

    private $_name;
    private $_email;
    private $_password;

    public function getUser($username) {
        global $db;

        return $db->query(whatever);
    }
}