CodeIgniter: unable to access $ of this function inside

I use CodeIgniter, and one of my views turned out to be quite large, so I moved part of the code to a function in the same file:

function html_stuff()
{
    $posts = $this->db->query('select * from posts');
}

When I run this code, I get the following error:

Fatal error: using $ this if not in the object context in /somepath/view.php

+3
source share
1 answer

You can either pass a function $this

function html_stuff($ci) {
    $ci->db->query('select * from posts');
}
html_stuff($this);

Or use get_instance()

function html_stuff() {
    $ci = &get_instance();
    $ci->db->query('select * from posts');
}

See: http://ellislab.com/codeigniter/user_guide/general/creating_libraries.html

+7
source

All Articles