我有两门课:
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
发布于 2011-06-27 14:39:33
虽然我不完全确定为什么要从Users类继承MySQL。但不管怎样,如果你真的需要那样做的话。
而不是
$this->_conn = new MysqlDB($host, $username, $password, $db);做:
parent::__construct($host, $username, $password, $db);你不需要$this->_conn就用$this->_mysql
我相信MysqlDB类将采用单例模式。用户类只需使用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);
}
}https://stackoverflow.com/questions/6494477
复制相似问题