I am trying to create my own library so i can handle custom areas in my application. i have a small library located at application/libraries which i called randomizer. it looks like this:
Class Randomizer {
public function __construct()
{
parent::_construct();
$CI =& get_instance();
$CI->load->library('session');
$CI->load->database();
}
function test_function($name)
{
return 'Hi dear' . $name . 'welcome back!';
}
}
In my Controller i tried to test out the simple test_function:
public function index()
{
echo($this->Randomizer->test_function('John'));
exit;
}
And I am getting the following error
Call to a member function test_function() on a non-object
There are couple of possible errors i can see. first you are not loading the library you created inside your controller. in case you don't use $this->load->library('randomizer');
right before you call the library funcion. if you are going to use the library all over the controller then load it via the controller __consturct. Also i guess you are not extending an existing Class so the parent::_construct()
is not needed. make sure you understand why you are using a library and when you should use helpers. Read more about Codeigniter Libraries
Please look closely to the documentation. There are a few problems.
First of all it seems that you have either not loaded the library ($this->load->library('randomizer')
), otherwise you would get a syntax error because your are calling parent::_construct()
, instead of parent::__construct
. And you do not have to call that function anyway, because your class doesn't have a parent (it doesn't extend
a class...).
Furthermore, although you declare your class with a capital, the variable will be lowercase. So you should call $this->randomizer->test_function()