我是以 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 的新手,但我认为通过在连接函数中返回该变量,我可以通过在外面创建类来访问它。
感谢帮助,谢谢。
在外面使用它时,您可以通过实例访问类变量...
$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;
您需要更改:
$mysqli->connect_errno
自:
$this->mysqli->connect_errno
Fatal error: Call to a member function prepare() on a non-object in...
这始终意味着,您调用方法的东西不是对象。在您的情况下:mysqli 未初始化。
一般提示:连接看起来像一些东西,应该在构造函数中。
class d {
public function __construct($db_host, $db_user, $db_password, $db_name){
$this->mysqli = new mysqli($db_host, $db_user, $db_password, $db_name);
if ($this->mysqli->connect_errno) {
return "Sorry Andre, but you seem to have messed up the DB connection :(";
}
}
public $mysqli;
}
$foo = new d('host', 'user', 'pass', 'dbname');
$foo->mysqli->prepare("something");
因此,当您获取此类的实例时,它会自动初始化。同样通过这种方式,每次要初始化时,您都可以保存一行。