[英]PHP Problem accessing the global variable
我在 PHP 中遇到全局變量問題。 我有只包含以下數據的 mysqli 配置文件:
$mysqli = new mysqli("localhost", "user", "pass", "db");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
我在另一個文件上有以下課程:
class user{
function username_exists($username){
global $mysqli;
if ($stmt = $mysqli->prepare("SELECT username FROM users WHERE username=?")) {
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->store_result();
$count=$stmt->num_rows;
$stmt->close();
}
return ($count > 0 ? true : false);
}
...
some more functions
...
}
現在這很好用,但是在我之前關於 SO 的問題中,有人告訴我,像我在上面的課程中所做的那樣訪問全局變量是一種不好的做法。 所以,我試圖通過以下方式在構造函數中傳遞全局變量:
private $mysqli;
function __construct()
{
global $mysqli;
$this->mysqli = $mysqli;
}
function username_exists($username){
//global $mysqli;
if ($stmt = $this->mysqli->prepare("SELECT username FROM users WHERE username=?")) {
我收到以下錯誤:
Fatal error: Call to a member function prepare() on a non-object in...(line number)
你能告訴我它有什么問題以及如何解決這個問題嗎? 謝謝。 編輯:抱歉 __construct 的拼寫錯誤。 在這里打字只是錯誤,錯誤不是因為這個。
嗯......在你的構造函數中使用global
有點勝過這一點。 考慮將其作為參數__construct($mysqli)
傳入。
public function __construct($mysqli)
{
$this->mysqli = $mysqli;
}
您在此處嘗試執行的操作稱為依賴項注入。
我認為問題是您輸入錯誤__construct
嘗試將您的__cuntruct
更改為構造函數的正確名稱。
username_exists 中的全局也是無用的。
您還應該編寫一個將變量作為參數的構造函數,並避免完全使用 global :
class User {
var $mysqli;
function __construct($mysqli) {
$this->mysqli = $mysqli;
}
[ ... some functions ... ]
}
您必須像這樣創建對象:
$myuser = new User($mysqli);
$myUser->prepare();
您的構造函數沒有被調用,因為它根本不是構造函數
__cuntruct
應該
__construct
所寫的代碼並不是 SO 上的其他人試圖鼓勵你做的。
function __construct($mysql_handler){
$this->mysql = $mysql_handler;
}
這是在構造時將參數傳入對象范圍。 當您創建對象的實例時,您將傳入 MySQL 句柄。
$mysqli = new mysqli("localhost", "user", "pass", "db");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$u = new User($mysqlli);
然后您應該能夠在屬性本身上調用 mysqli 成員函數。
您的構造函數也拼錯了。 它只能與魔術方法名稱__construct()
一起正常工作。
幾件事。 我認為如果您將__cuntruct
更改為__construct
。
您仍在使用username_exists
函數中的global
聲明。 為什么不直接在構造函數中傳遞$mysqli
變量?
function _construct($mysqli) {
$this->mysqli = $mysqli;
}
那么你在課堂上沒有全局變量。
刪除global $mysqli;
在函數username_exists()
,它沒有意義。
global $mysqli;
不需要/沒有意義,因為您希望此變量在對象的上下文中存儲對連接的引用。
將__cuntruct()
更改為__construct()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.