在類中使用全局變量我正在嘗試創建一個分頁類,并從類外部使用一個變量。但是它給了我致命的錯誤“調用非對象上的成員函數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個贊
$db
get_records
$records = $pagination->get_records("SELECT * FROM `table`", $db);
public function get_records($q, $db) {

SMILET
TA貢獻1796條經驗 獲得超4個贊
添加回答
舉報
0/150
提交
取消