Question

Is it safe to overwrite the super-global $_SESSION with a specialised session object?

class SessionObject implements ArrayAccess { ... }

...

// Session data has just been deserialised from store.
$_SESSION = new SessionObject( $session_data );

...

// Using session object...
$_SESSION['key'] = 27;
$x = $_SESSION->get_data('key2', 'default-value');
Was it helpful?

Solution

While this may work, I don't think it's sensible behaviour. The principle of least surprise applies, in my opinion, to programming as much as to user interface design. If you overwrite the default behaviour of $_SESSION in your script, that's going to confuse the hell out of some future programmer who has to deal with your code.

I think it's a hack -- and an unpleasant one -- to abuse the super-global nature of $_SESSION in this way.

Better, in my opinion, would be to write a class with static methods to get and set your data:

class Session {
    public function get($key, $defaultValue = null) {
        // do some code to get the value for $key, and return $defaultValue if there is none
    }

    public function set($key, $value) {
        // do some code to set $key
    }
}

You could then access this with Session::get('someKey') or Session::get('someKey', 'default') and Session::set('someKey', 'someValue').

Since classes are inherently global, you could access this from anywhere in your code. It is less surprising, and will result in less confusion down the line.

If you did want to use object methods for some design reason, it might be best to implement the Singleton pattern.

OTHER TIPS

Seems a little risky to me. Have you checked out the session_set_save_handler method? It lets you designate your own handler to use, instead of trying to overwrite $_SESSION.

If you deal with session handling and storage yourself, then you can do whatever you please. The $_SESSION superglobal can be used like any other variable in that regard.

It's only PHPs default session handler which treats it specially. It expects a normal array there (and must not be numerically indexed as well). If you wanted to use that again, you would require to undo the fancy ArrayObject wrapping with a shutdown call:

register_shutdown_function(function(){
    $_SESSION = (array)$_SESSION;
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top