Codeigniter 3报错:Unable to locate the specified class: Session.php 求助
Hey there, I’ve run into this exact issue before when working with CI3 controller inheritance—let’s break down the most likely causes and fixes step by step:
1. Make Sure the Session Library is Loaded Properly
This error often pops up because the Session library isn’t being initialized when your child controller runs. Here’s how to fix it:
- Auto-load the Session library: Open
application/config/autoload.phpand add'session'to the$autoload['libraries']array. This ensures it’s available across all controllers. - Manual load in parent controller: If you don’t want to auto-load, add
$this->load->library('session');to the constructor of your parent controller (e.g., ControllerB). Just make sure you call the parent constructor first:class ControllerB extends CI_Controller { public function __construct() { parent::__construct(); // Critical: Initialize CI's core first $this->load->library('session'); } }
2. Fix Controller Inheritance Loading Issues
CI3 doesn’t automatically load sibling controllers in the application/controllers directory. If you’re extending a controller that’s in the same folder (e.g., ControllerA extends ControllerB), you need to manually include the parent controller file:
// At the top of ControllerA.php require_once APPPATH . 'controllers/ControllerB.php'; class ControllerA extends ControllerB { public function __construct() { parent::__construct(); // Don't forget this! } public function your_method() { // Now calling parent methods won't trigger the Session error } }
If you’re using a custom base controller (like MY_Controller), ensure it’s placed in application/core/ with the correct naming convention (e.g., MY_Controller.php with class name MY_Controller)—CI will auto-load these core controllers automatically.
3. Check Filename & Class Name Case Sensitivity
CI3 is case-sensitive with file names, especially on Linux servers. Double-check:
- The Session library file is named
Session.php(notsession.phporSESSION.php) inapplication/libraries/ - Your controller filenames match their class names exactly (e.g.,
ControllerB.phpcorresponds toclass ControllerB)
4. Verify Parent Constructor is Called in Child Controller
Even if your parent controller loads the Session library, if your child controller’s constructor doesn’t call parent::__construct(), none of the parent’s initialization code (including Session loading) will run. Always include this line in your child controller’s constructor:
public function __construct() { parent::__construct(); // Your child-specific setup here }
Start with these steps—9 times out of 10, the issue is one of these four things. Let me know if you still hit snags after checking!
内容的提问来源于stack exchange,提问作者issei-kun

