Search code examples
phpcodeignitercodeigniter-2

Why ERROR in Codeigniter


I have error, please help

A PHP Error was encountered

Severity: Notice

Message: Undefined property: User::$user_model

Filename: controllers/user.php

Line Number: 15

Backtrace:

File: C:\wamp\www\apcodeigniter\application\controllers\user.php Line: 15 Function: _error_handler

File: C:\wamp\www\apcodeigniter\index.php Line: 292 Function: require_once

Line 15 is: public function get()

public function get()
{
    $this->user_model->get();
}

Solution

  • You haven't loaded the model yet.

    Try changing the get method in User controller to -

    public function get()
    {
        $this->load->model('user_model');
        $this->user_model->get();
    }
    

    What I usually do in controllers, which are going to be depedent on that model, and each method would require some method of that model.

    /*
     * Load the model in the controller's constructor
     */
    class User extends CI_Controller
    {
        function __construct()
        {
            parent::_construct(); //This is important if you're adding a constructor in the Controller, so that it can properly initialize the scope of CI_Controller in itselves
            $this->load->model(array('user_model'));
        }
    
        public function get() //public here really isn't necessary, but kept it for understanding
        {
            $this->user_model->get();
        }
    }
    

    Hope this helps.