CodeIgniter: Class 'CI_Controller' not fou

2019-01-12 09:58发布

问题:

I've extended CodeIgniter controller by adding MY_Controller.php in Application/Core folder. It works fine, but Now when I add following code on error_404.php page in Application/errors, I get error.

Code causing problem:

<?php $ci =& get_instance();?>
<?php $this->ci->load->view('header')?>

Error:

Fatal error: Class 'CI_Controller' not found in path\to\system\core\CodeIgniter.php on line 231

The line 231 of the system\core\CodeIgniter.php is:

function &get_instance()
    {
        return CI_Controller::get_instance(); 
    }

How can I fix this so that I can load view in the error_404.php without changing anything in system files.

PS. I'm using latest version.

Thanks.

回答1:

I don't think CI_Controller is loaded yet. The Exception class is handling the 404 page output using an include.

In the old days, I used to use straight includes to piece together a template, or do a file_get_contents() or cURL request to my 404 page URL, but they finally did something about it. In 2.0 you can define a custom 404 page in routes.php:

$route['404_override'] = 'controller/method/parameter';

It's still not a perfect solution, but the easiest way now is just to use the route.

Note that base_url()."controller/method/parameter" must be a valid url, and you should make sure to set a 404 header in the controller that outputs the page too (it's not done automatically for some reason).



回答2:

I had this problem when following the CodeIgniter tutorial here: http://codeigniter.com/user_guide/tutorial/static_pages.html

The problem was I tried to access the url:

localhost/CodeIgniter_2.1.1/application/controllers/pages.php

instead of addressing the url:

localhost/CodeIgniter_2.1.1/index.php/pages/view

I know it has been around 18 months since you asked that question but maybe it can help someone else :)



回答3:

or you could try this, perhaps bit dirty but i think it will work for me

update your exception to

function show_404($page = '', $log_error = TRUE)  {
   if ($log_error)   {
     log_message('error', '404 Page Not Found --> '.$page); 
   } 
   header('Location: http://www.########.###/error/error_404');  
   die();
}

then just create controller to handle the redirect, perhaps with different errors you can use the same controller

that way you will get your dynamic header and footer



回答4:

Try:

<?php $ci =& get_instance();?>
<?php $ci->load->view('header')?>

Once you assigned the instance of CI to $ci you can just use $ci->load->view('header) throughout your file.