简体   繁体   中英

CodeIgniter “Using $this when not in object context” in function

how I can replace $this variable in this code? I know that it is incorrect to use $this in functions, but I don't know how I may replace that.

function get_dates($id) {
        $class = $this->db->query("SELECT * FROM schedule WHERE class_id='".$id."'");
        $class = $class->result_array();
        return $class;
    }

PS. I don't won't to work with mysql with standart php features and I strongly believe that it is possible to solve this problem with CI featues.

If you want to access the CI framework from inside a plain function, you need to get an instance of CI.

function get_dates($id) {
    $ci =& get_instance();

    $class = $ci->db->query("SELECT * FROM schedule WHERE class_id='".$id."'");
    $class = $class->result_array();
    return $class;
}

If You are in Helpers or library and want to access the controller object you have to user:

$ci =& get_instance();

Once you will get the controller object you can access any public method or member through $ci reference, you can get the model object as well by setting up a getter method to get the object and then simply reference that object for querying the db.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM