参见英文答案 > Call to a member function on a non-object 8个
我是新手以OOP方式使用PHP但发现我的数据库连接类有问题.
这里有一个mysqli连接类的文件
$db_name = 'dbname';
$db_user = 'dbuser';
$db_password = 'dbpassword';
$db_host = 'localhost';
class database {
public $mysqli;
public function connect($db_host, $db_user, $db_password, $db_name){
$this->mysqli = new mysqli($db_host, $db_user, $db_password, $db_name);
if ($mysqli->connect_errno) {
return "Sorry Andre, but you seem to have messed up the DB connection :(";
}
}
}
$newConnection = new database;
$newConnection->connect($db_host, $db_user, $db_password, $db_name);
然后我想在另一个文件中的数据库连接中使用变量$mysqli – 这是使用$mysqli变量连接到数据库的简单插入.我将上面的内容包含在连接文件中,但是当我在数据库类中调用该方法时,似乎没有返回$mysqli变量.我得到PHP错误说…
Fatal error: Call to a member function prepare() on a non-object in...
我见过那个用
global $mysqli;
然而,我想以正确的方式去做,因为我听说这不是好的做法.
我知道我可能在这里做错了,因为我不熟悉使用OOP但是我假设通过在connect函数中返回该变量,我可以通过在外部创建类来访问它.
感谢帮助,
谢谢.
解决方法:
在外面使用它时,您可以通过实例访问类变量…
$newConnection = new database;
$newConnection->connect($db_host, $db_user, $db_password, $db_name);
$newConnection->mysqli /* here you have access from outside */
从里面你使用关键字$this …
// like this from inside
if ($this->mysqli->connect_errno) {
return "Sorry Andre, but you seem to have messed up the DB connection :(";
}
如果您想保护您的变量不受外部访问使用:
private $mysqli;
// instead of
public $mysqli;
标签:php,variables,scope,class
来源: https://codeday.me/bug/20190729/1569295.html