[英]Can't call database connection with $this
Whenever I'm trying to call $this->dbc
in Is_Staff
it returns an error saying: 每当我尝试在Is_Staff
调用$this->dbc
, Is_Staff
返回错误消息:
Fatal error: Using $this when not in object context
And I'm not quite sure why it's doing this. 我不太确定为什么要这么做。 I have tried making $dbc global but that doesn't seem to do anything. 我试过将$ dbc设置为全局,但这似乎无济于事。
Class BoardDatabase {
public $dbhost = "localhost"; // Host
public $dbuser = "root"; // Username
public $dbpass = ""; // Password
public $dbname = "NecBoard"; // Database
public function __construct($dbhost, $dbuser, $dbpass, $dbname) {
$this->dbc = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname) or die("Couldnt connect to the database! " . mysqli_errno);
if(!$this->dbc) {
die("Could not connect to database: " . $this->dbc->connect_errno());
}
}
public static function Is_Staff($type, $bool) {
if($type == "mod") {
if($bool == true) {
$IsStaff = $this->dbc->prepare("SELECT is_mod FROM users WHERE id = ?");
$IsStaff->bind_param("s", $_SESSION["id"]);
$IsStaff->execute();
$IsStaff->bind_result($is_mod);
$IsStaff->store_result();
if($IsStaff->num_rows >= 1) {
$IsStaff->fetch();
if($is_mod >= 1) {
return true;
} else {
return false;
}
}
} else {
return false;
}
}
}
}
Problems 问题
Firstly, you are accessing the $dbc
variable as a context of the object BoardDatabase
when it is not even a property of the object itself. 首先,当$dbc
变量甚至不是对象本身的属性时,您将它作为对象BoardDatabase
的上下文来访问。
Secondly, you cannot access a variable using the $this
in a static context. 其次,您不能在静态上下文中使用$this
访问变量。
Solution 解
Declare the variable $dbc
at the top as a static variable: 在顶部将变量$dbc
声明为静态变量:
public static $dbc;
And access it this way in the object context: 并在对象上下文中以这种方式访问它:
self::$dbc
This should solve your problem. 这应该可以解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.