Chris Pynegar
Chris Pynegar

Reputation: 183

Using CodeIgniter libraries through static methods

I am having trouble trying to call CodeIgniter methods in my static functions, just using $this doesn't work because its not in object context, the static keyword doesn't work either. This an example of the code in my core model, the $table variable is successfully defined from another model like posts.

class MY_Model extends CI_Model {

    protected static $table;

    public function __construct() {
        parent::__construct();
    }

    public static function find_all() {
        $this->db->select('*');
        $sql = $this->db->get(static::$table);
        return $sql->result();
    }

}

Upvotes: 0

Views: 3800

Answers (4)

Joe Shmoe
Joe Shmoe

Reputation: 179

Codeigniter doesn't generally support static methods I believe and they are really an attempt to shoehorn procedural code into object oriented code.

Anyway, I think your best bet is to either use the class without static methods, or turn your code into a "helper". A helper is just an old school function library. You would create it under the helpers folder and it can be loaded with $this->load->helper('helper_name'). You can then call the function as in normal procedural code, in other words 'find_all()'

Hope this helps. First time contributor :)

Upvotes: 0

Code Prank
Code Prank

Reputation: 4250

The codeigniter built in loader class automatically instantiates the class. There is no support to use classes without instantiating. You can manually include your file in the model file then you can use it. For more details check out this thread: http://codeigniter.com/forums/viewthread/73583/

Upvotes: 3

filip
filip

Reputation: 1503

If $this doesn't work you can get around this like this:

$CI =& get_instance();
$CI->db->...

Upvotes: 5

JvdBerg
JvdBerg

Reputation: 21856

What you want is a refence to the static var in the class, so use:

class MY_Model extends CI_Model {

    protected static $table;

    public function __construct() {
        parent::__construct();
    }

    public static function find_all() {
        $this->db->select('*');
        $sql = $this->db->get(self::$table);
        return $sql->result();
    }

}

And, of course, $table does need to have a value!

Upvotes: 0

Related Questions