将mysqli对象传递给类

时间:2012-11-07 14:22:06

标签: php

我想将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

有什么问题?

1 个答案:

答案 0 :(得分:2)

访问班级中的课程属性$this时,您需要使用$_link

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

$_link = $link;

这应该是:

$this->_link = $link;

使用getPageContent()方法:

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

这应该是:

$result = mysqli_query($this->_link,$query);