Alex Rivera | Logout

Is using superglobals directly good or bad in PHP?

Asked 2010-08-16T23:24:52.123
10

So, I don't come from a huge PHP background—and I was wondering if in well formed code, one should use the 'superglobals' directly, e.g. in the middle of some function say $_SESSION['x'] = 'y'; or if, like I'd normally do with variables, it's better to send them as arguments that can be used from there, e.g:

class Doer {
    private $sess;
    public function __construct(&$sess) {
        $this->sess =& $sess;
    }
} 

$doer = new Doer($_SESSION);

and then use the Doer->sess version from within Doer and such. (The advantage of this method is that it makes clear that Doer uses $_SESSION.)

What's the accepted PHP design approach for this problem?

Edit
Report

1 Answer

4

I know this question is old but I'd like to add an answer.

mario's classes to handle the inputs is awesome.

I much prefer wrapping the superglobals in some way. It can make your code MUCH easier to read and lead to better maintainability.

For example, there is some code at my current job the I hate! The session variables are used so heavily that you can't realistically change the implementation without drastically affecting the whole site.

For example,

Let's say you created a Session class specific to your application.

class Session
{
    //some nice code
}

You could write something like the following

$session = new Session();
if( $session->isLoggedIn() )
{
   //do some stuff
}

As opposed to this

if( $_SESSION['logged'] == true )
{
   //do some stuff
}

This seems a little trivial but it's a big deal to me. Say that sometime in the future I decide that I want to change the name of the index from 'logged' to 'loggedIn'.

I now have to go to every place in the app that the session variable is used to change this. Or, I can leave it and find someway to maintain both variables.

Or what if I want to check that that user is an admin user and is logged in? I might end up checking two different variables in the session for this. But, instead I could encapsulate it into one method and shorten my code.

This helps other programmers looking at your code because it becomes easier to read and they don't have to 'think' about it as much when they look at the code. They can go to the method and see that there is only ONE way to have a logged in user. It helps you too because if you wanted to make the 'logged' in check more complex you only have to go to one place to change it instead of trying to do global finds with your IDE and trying to change it that way.

Again, this is a trivial example but depending

answered 2012-04-16T03:25:08.950

Your Answer