I recently ran into a problem using CodeIgniter where I kept receiving the error: “Call to a member function on a non-object”. This problem occurred when I was trying to use a method from one model from within another model.
I have a model named mGalleryImages. Within this model, I have a method named addGalleryImages. Within this method, I load another model and tried to call a method from the loaded model:
function addGalleryImages(){
...
$this->load->model('mUtilImages');
...
$this->mUtilImages->setImageFile($_FILES['uploadFile']);
}
I receive the error when the
setImageFile method is called. The problem is that when the model sees “$this”, it is looking for a method within the
mGalleryImages model. The solution was to use a CodeIgniter function named get_instance().
function addGalleryImages(){
...
$CI =& get_instance();
$this->load->model('mUtilImages');
...
$CI->mUtilImages->setImageFile($_FILES['uploadFile']);
}
Easy enough, but I would never have thought that this was the problem. I played with this code for hours, trying to figure out why it didn’t work similarly to a regular PHP class. But now I know.