我在使用该类的第二个方法中在我的类的一个方法中实例化的 mysqli 对象时遇到问题。谁能帮助我了解我可能做错了什么?这是我的两个类方法的样子:
function connect() {
$mysqli = new mysqli($this->host, $this->user, $this->pass, $this->db);
if($mysqli->connect_errno) {
printf("Connect failed: %s'n", $mysqli->connect_error);
exit();
}
else {
echo 'Successful';
}
}
public function query($sql) {
$this->sql = $sql;
$mysqli->connect();
$result = $mysqli->query($this->sql);
while ($row = $result->fetch_assoc()) {
printf ("$s (%s)'n", $row['name']);
echo "<br>";
}
$result->free();
$mysqli->close();
}
我认为我的麻烦是公开实例化的对象。
更新:这是当前我拥有的整个类,当尝试在查询方法中执行一行时,脚本正在死亡:
$this->mysqli->connect();
class database {
public $host = "host";
public $user = "user";
public $pass = "pw";
public $db = "dbname";
public $sql;
private $mysqli;
function __construct() {
echo "new class object created";
echo "<br><br>";
}
function connect() {
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->db);
if($this->mysqli->connect_errno) {
printf("Connect failed: %s'n", $mysqli->connect_error);
exit();
}
else {
echo 'Successful';
}
}
public function query($sql) {
$this->sql = $sql;
echo "test1";
$this->mysqli->connect();
echo "test2";
$result = $this->mysqli->query($this->sql);
echo "test3";
while ($row = $result->fetch_assoc()) {
printf ("$s (%s)'n", $row['name']);
echo "<br>";
}
$result->free();
$this->mysqli->close();
}
}
echo "test2"; does not execute.
你的问题是变量范围。如果不global
'ly 指定它,则无法以您想要的方式访问它。
你最好坚持最佳实践并做这样的事情:
private $mysqli;
function connect() {
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->db);
if($this->mysqli->connect_errno) {
printf("Connect failed: %s'n", $mysqli->connect_error);
exit();
}
else {
echo 'Successful';
}
}
您注意到我们如何将其定义为$this
(在对象内)。现在您将能够访问它:
public function query($sql) {
$this->sql = $sql;
$this->connect();
$result = $this->mysqli->query($this->sql);
while ($row = $result->fetch_assoc()) {
printf ("$s (%s)'n", $row['name']);
echo "<br>";
}
$result->free();
$this->mysqli->close();
}
方法是一个函数。就像任何其他函数一样,您在函数内声明的变量不能在该函数外部访问。