Is it recommended to create a function for accessing session variables in PHP for better reusability and readability?

Creating a function for accessing session variables in PHP can improve code reusability and readability. By encapsulating the logic for retrieving session variables within a function, you can easily reuse it throughout your codebase without duplicating code. This also makes your code more maintainable and easier to understand, as the function name can provide a clear indication of its purpose.

function getSessionVariable($key) {
    if (isset($_SESSION[$key])) {
        return $_SESSION[$key];
    } else {
        return null;
    }
}

// Example of using the function
$userId = getSessionVariable('user_id');
if ($userId) {
    echo "User ID: " . $userId;
} else {
    echo "User ID not found in session.";
}