[英]PHP Class Object inside method
我在使用在类的第二个方法中的类的一个方法中实例化的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
指定,则无法以所需方式访问它。
您最好坚持最佳实践并执行以下操作:
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();
}
方法是一种功能。 与其他任何函数一样,在函数内部声明的变量无法在该函数外部访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.