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');
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
$_SESSIONin 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
$_SESSIONin this way.Better, in my opinion, would be to write a class with static methods to get and set your data:
You could then access this with
Session::get('someKey')orSession::get('someKey', 'default')andSession::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.