查询功能神秘破解[关闭]

I have a Database class which has multiple functions to execute queries. One of them is the simplest of them all:

public function query($query) {
    return $this->_link->query($query);
}

$this->_link->query works in other cases, so it should work here. From a file that has an instance of a class, I do this:

function createLineChart() {

    $query = "select * from tags";
    $result = $db->query($query);

    // do something with result
}

createLineChart();

but it breaks on the $result line. The query is also valid, I've testid it. Am I missing something?

Your problem is $db is out of scope of the createLineChart() function. You can either use the global method:

function createLineChart() {
    global $db; // <-- make the db var become available
    $query = "select * from tags";
    $result = $db->query($query);

    // do something with result
}

Or pass the $db object to the function as an argument:

function createLineChart($db) {

    $query = "select * from tags";
    $result = $db->query($query);

    // do something with result
}

createLineChart($db);

More info about Variable Scope on the Manual.

If $db is a class variable, then you need to refer it as:

$result = $this->db->query($query);
function createLineChart() {
    var_dump($db);
    // this should probably return 'undefined'
    global $db;
    // so globalize it!
    $query = "select * from tags";
    $result = $db->query($query);
    // do something with result
}