Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe to Overwrite super-global $_SESSION?

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');
like image 758
Lea Hayes Avatar asked Feb 24 '23 21:02

Lea Hayes


1 Answers

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.

like image 109
lonesomeday Avatar answered Mar 05 '23 18:03

lonesomeday