codeigniter 4 set session variable $session = \Config\Services::session(); globally

codeigniter 4 set session variable $session = \Config\Services::session(); globally

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Why You Can't Access Session Variables Declared in Controller Files

A common stumbling block when migrating from CodeIgniter 3 or using legacy patterns is the assumption that variable scope works identically across different PHP environments. In CodeIgniter 4, developers often encounter a specific issue where a session service instance declared at the top of a controller file feels inaccessible within class methods.

The core misunderstanding usually stems from how PHP handles namespace scoping and static initialization versus instance properties. When you declare $session = \Config\Services::session(); directly above the class Home extends BaseController declaration, that variable exists in the global scope of the file (or the specific namespace block if not careful), but it is not a property of the BaseController class itself.

In PHP, variables declared outside of a class definition are local to that execution context. When your controller methods execute, they run within the instance of the Home object. Methods inside the class do not automatically inherit access to variables defined in the global scope of the file unless those variables are explicitly attached to the object or accessed via static globals (which is generally discouraged). This is why defining the variable above the class definition results in a "undefined variable" error when you try to use it inside public function index().

The Proper Approach: Dependency Injection

The idiomatic way to handle dependencies like the session service in CodeIgniter 4 is to rely on the framework's built-in dependency injection system. This approach ensures that your controllers remain decoupled and testable.

You should not manually instantiate services inside your controller classes. Instead, you can inject the session service directly into the __construct method or use the container to resolve it when needed. However, the most straightforward pattern for accessing the session in a specific controller is to inject it as a property in the constructor:

namespace App\Controllers;

use CodeIgniter\Controller;
use Config\Services;

class Home extends BaseController
{
    protected $session;

    public function __construct()
    {
        parent::__construct();
        $this->session = Services::session();
    }

    public function index()
    {
        // Now this works because $this->session is a class property
        $user_id = $this->session->get('user_id');
        
        if ($user_id) {
            return view('welcome_message');
        }
        
        return redirect()->to('/login');
    }
}

By moving the initialization into the __construct method, you attach the session instance to the specific controller instance. Every time the framework creates a new Home object (which happens on every request), it runs this constructor, ensuring fresh, valid state for that execution context.

Using the Global Helper for Truly Global Access

If your requirement is strictly to access the session variable globally across all controllers without injecting it into each class, you should bypass the controller class entirely and use the helper function provided by the framework. CodeIgniter 4 registers a session() helper that resolves the service from the container every time it is called.

This pattern effectively gives you global access without manually managing the lifecycle of the session object in your code:

namespace App\Controllers;

use CodeIgniter\Controller;
use Config\Services;

class Home extends BaseController
{
    public function index()
    {
        // Accessing via the helper is treated as a global call
        $session = Services::session(); 
        
        // Or using the helper if registered in app/Config/Services.php
        // However, direct Service::session() is preferred for clarity
        
        return response()->json(['message' => 'Hello']);
    }
}

Alternatively, if you want to set a variable that persists across views and controllers without passing it as data, ensure you are using the Session library's setFlashData or similar methods rather than trying to store raw variables in a global scope.

Why Not Global Variables?

Attempting to use a global $session variable defined at the top of your file violates several architectural principles:

  1. State Management: In web applications, each request is independent. Storing the session object in a global variable can lead to stale state if not properly refreshed by the framework's middleware.
  2. Testing Difficulty: If you need to mock the session service for unit tests, having it hard-coded as a global variable makes injecting mocks significantly harder compared to constructor injection or helper functions.
  3. Readability: It is immediately obvious to any developer reading your code that $session inside index() refers to Services::session(), whereas a global variable implies shared state that might not exist in other parts of the application.

Final Configuration Note

Ensure that the session library is properly configured in app/Config/Session.php. While the default configuration works out of the box, customizing driver types or cookie settings should happen there, not by re-instantiating the service manually in every controller.

By adhering to the pattern of instantiating services within the constructor or using the framework's helpers, you align your code with CodeIgniter 4's design philosophy, ensuring robustness and maintainability as your application scales.

Our network