Home

Codeigniter instance inside a custom library or helper

Created October 20, 2010

When first creating your own custom helpers or libraries inside of codeigniter you may find yourself not able to use some of the core libraries and helpers provided by codeigniter. For instance, lets say that you wanted to call the database class ($this->db->get...) from inside one of your own libraries or helpers. Inside one of your custom libraries or helpers you will not be able to call the $this function; therefore, you have to use the get_instance() function and store the Codeigniter object in that variable. This can easily be done using the following line of code:

$CI =& get_instance();

Now, inside of one of your libraries or helpers, you could perform the following functionality to access the database library:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

	
if ( ! function_exists('helper_function'))
{
	function helper_function($argument = '')
	{
		$CI =& get_instance();
		$CI->db->get('database_table');
	}
}
?>