在类中使用全局变量我正在尝试创建一个分页类,并从类外部使用一个变量。但是它给了我致命的错误“调用非对象上的成员函数Query()”。这是索引文件:$db = new DB_MySQL("localhost", "root", "", "test");
// connect to the databaseinclude_once("pagi.php");
$pagination = new pagi();$records = $pagination->get_records("SELECT * FROM `table`");这是pagi.php文件:class pagi {
public function get_records($q) {
$x = $db->query($q);
return $db->fetch($x);
}}是否可以从类的外部使用这个变量,而无需在类中创建一个新变量?
4 回答
狐的传说
TA贡献1804条经验 获得超3个赞
<?php//define a database classclass DB {
//the static connection.
//This is available to all instances of the class as the same connection.
private static $_conn;
//store the result available to all methods
private $result;
//store the last query available to all methods
private $lastQuery;
//static connection function. connects to the database and stores that connection statically.
public static function connect($host, $user, $pass, $db){
self::$_conn = mysqli_connect($host, $user, $pass, $db);
}
//standard function for doing queries. uses the static connnection property.
public function query($query){
$this->lastQuery = $query;
$this->result = mysqli_query(self::$_conn, $query);
//process result, return expected output.
}}//create connection to the database, this connection will be used in all instances of DB classDB:
:connect('local', 'DB_USER', 'DB_PASS');//create instance to query$test = new DB;
//do query$test->query("SELECT * FROM TABLE");//test functionfunction foo(){
//create instance to use in this function
$bar = new DB;
//do query
$bar->query("SELECT * FROM OTHER_TABLE");
//return results
return $bar->fetchArray();}
智慧大石
TA贡献1946条经验 获得超3个赞
$dbget_records
$records = $pagination->get_records("SELECT * FROM `table`", $db);public function get_records($q, $db) {
SMILET
TA贡献1796条经验 获得超4个赞
添加回答
举报
0/150
提交
取消
