1

我想将一个 mysqli 对象传递给一个类。我在一个文件中创建对象:

$host = 'host';
$user = 'username';
$pw = 'pw';
$db = 'db';

$link = new mysqli($host,$user,$pw,$db);

包含在一页中:

include 'php/mysql.php';
include 'php/classes/Class.Dataconnector.php';
$dc = new Dataconnector($link);

这个类看起来像这样:

class Dataconnector {
    protected $_link;
    protected $_stub;

    function __construct(mysqli $link) {
        $_link = $link;
    }

    public function getPageContent($stub) {
        $query = "select * from contents where pageId = (select id from pages where stub = '$stub')";
        $result = mysqli_query($_link,$query);
        return $result;
    }
}

但我得到这个错误:

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in \php\classes\Class.Dataconnector.php on line 18

怎么了 ?

4

1 回答 1

2

$this访问类中的类属性时需要使用$_link

在您的构造函数中,您有:

$_link = $link;

这应该是:

$this->_link = $link;

在您的getPageContent()方法中,您有:

$result = mysqli_query($_link,$query);

这应该是:

$result = mysqli_query($this->_link,$query);
于 2012-11-07T14:29:20.483 回答