How can PHP sessions be handled using object-oriented programming principles for better organization and scalability?

To handle PHP sessions using object-oriented programming principles for better organization and scalability, we can create a Session class that encapsulates session management functionality. This class can provide methods for starting, destroying, and accessing session data, making it easier to manage sessions in a structured and reusable way.

<?php

class Session {
    public function __construct() {
        session_start();
    }

    public function set($key, $value) {
        $_SESSION[$key] = $value;
    }

    public function get($key) {
        return $_SESSION[$key] ?? null;
    }

    public function destroy() {
        session_destroy();
    }
}

// Example of using the Session class
$session = new Session();
$session->set('user_id', 123);
$user_id = $session->get('user_id');
echo $user_id; // Output: 123

$session->destroy();