-1

我正在尝试使用 mysqli,尽管我已经尝试修复它几个小时,但它一直给我一个错误。

这是数据库类

class db {

    public $mysqli;

    function __construct(){
        $mysqli = new mysqli('host', 'user', 'password', 'database');
    }

    function clean($string){
        $string = $mysqli->real_escape_string($string);
    }

}

当我尝试在这样的测试页面中调用它时,

$db = new db();
$db->clean("hi");

我收到一个错误:

注意:未定义变量:第 12 行 C:\xampp\htdocs\eat\class\db.class.php 中的 mysqli

致命错误:在第 12 行的 C:\xampp\htdocs\eat\class\db.class.php 中的非对象上调用成员函数 real_escape_string()

我在这里做错了什么吗?我已经在 stackoverflow 上搜索了很长时间的 php 手册,但似乎没有其他人面临这个错误。

4

2 回答 2

3

您正在$mysqli方法范围内使用变量。您应该使用$this来访问对象范围。

class db {

    public $mysqli;

    function __construct(){
        $this->mysqli = new mysqli('host', 'user', 'password', 'database');
    }

    function clean($string){
        return $this->mysqli->real_escape_string($string);
    }

}
于 2013-02-05T20:13:07.937 回答
0

你有没有听说过不在As is类方法中声明变量?

$this->引用变量范围时必须始终使用。

下面是如何访问变量的蓝图

class foo {

$who= "MyName";

function __construct() {

$this->who;

}

}

在上面的例子中,who你的函数内部引用了变量。

于 2013-02-05T20:16:28.670 回答