shuvo
shuvo

Reputation: 1956

error calling member function of alleged non-object in Codeigniter controller

I get the error

Fatal error: Call to a member function retrieve_products() on a non-object

The controller is:

<?php   
class Cart extends CI_Controller { // Our Cart class extends the Controller class  

   public function _construct()  
   {  
       parent::_construct(); // We define the the Controller class is the parent.  
       $this->load->model('Cart_model'); // Load our cart model for our entire class  
   }

   function index()  
   {  
      $data['products'] = $this->cart_model->retrieve_products(); // Retrieve an array with all products  
   }
}

The model is:

<?php   
class Cart_model extends CI_Model {

    function retrieve_products(){  
        $query = $this->db->get('products'); // Select the table products  
        return $query->result_array(); // Return the results in a array.
    }             
}

Upvotes: 0

Views: 351

Answers (3)

jco
jco

Reputation: 677

I want to say that your call

$data['products'] = $this->cart_model->retrieve_products();

Should be:

$data['products'] = $this->Cart_model->retrieve_products();

Ie: uppercase "C" in cart_model

Upvotes: 1

Code Prank
Code Prank

Reputation: 4250

I think its your typo error you have spelled construct function as _construct rather than __construct thats why codeigniter considers it as a function rather than a class constructor and model loading is limited to only that function.

Upvotes: 0

wallyk
wallyk

Reputation: 57764

Maybe we're using different versions (I have 1.7.2), but to declare a model, CI_ does not appear. My working code has the equivalent of:

class Cart_model extends Model

Also, the class should capitalized:

$this->Cart_model->retrieve_products();

(instead of)

$this->cart_model->retrieve_products();

Upvotes: 1

Related Questions