PHP Class 对象内部方法

PHP Class Object inside method

我在 class 的第二种方法中使用在我的 class 的一种方法中实例化的 mysqli 对象时遇到问题。谁能帮助我了解我可能做错了什么?这是我的两个 class 方法的样子:

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();
}

我认为我的麻烦是制作实例化对象public。

****更新:这是目前我拥有的全部 class,当尝试在查询方法中执行一行时,脚本快要死了:

$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();
}

一个方法就是一个函数。就像任何其他函数一样,您在函数内部声明的变量无法在该函数外部访问。