Call to a member function userdata() on a non-object

6.2k views Asked by At

Hi everybody I have a code that give me this error

Fatal error: Class 'MY_Controller' not found in C:\wamp\www\project\application\controllers\admin\home.php on line 3

I have no idea why it's showing this error…

The code of C:\wamp\www\project\application\controllers\admin\home.php is

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

class Home extends MY_Controller {

function index()
{
    redirect('admin/login');
}

function logout()
{
    $this->session->unset_userdata('logged_in');
    //session_destroy();
    redirect('admin/login');
}
}
?>

The code of C:\wamp\www\project\application\libraries\MY_Controller.php is

<?php

class MY_Controller extends CI_Controller {
public function __construct() {
    parent::__construct();
    if (!$this->session->userdata('logged_in')) {
        redirect('admin/login');
    }
}

}

And also if I place

class Home extends CI_Controller

instead of

class Home extends MY_Controller

in the

C:\wamp\www\project\application\controller\admin\home.php

file and try to load the

C:\wamp\www\project\application\libraries\MY_Controller.php

in the constructor of

C:\wamp\www\project\application\controllers\admin\home.php

it shows

Call to a member function userdata() on a non-object

Why so?

2

There are 2 answers

4
safarov On BEST ANSWER

You need to put class files to core instead of library folder when you extending System classes. Put MY_Controller.php in core folder.

2
Jakub On

Refer to the documentation: http://codeigniter.com/user_guide/general/core_classes.html

Core controllers need to be stored in application/core/

So when you extend an object, it will look for it there. Library folder is used for storage of 'external' libraries, which you must explicitly include in your controller:

Ex: $this->load->library('class name');

Info on libraries here: http://codeigniter.com/user_guide/general/libraries.html