views:

169

answers:

4

Is it a problem if you use the global keyword on variables you don't end up using? Compare:

function foo() {
    global $fu;
    global $bah;
    if (something()) {
        $fu->doSomething();
    } else {
        $bah->doSomething();
    }
}

function bar() {
    if (something()) {
        global $fu;
        $fu->doSomething();
    } else {
        global $bah;
        $bah->doSomething();
    }
}

I'm quite aware that using the second method makes maintaining this code much harder, and that it's generally preferred to put all your globals at the start of functions, so: Ignoring the difference in maintainability and code-styling of the two functions, is there a difference between these two in terms of overhead?

+8  A: 

If there is, it won't be (humanly) measurable, unless you are literally calling this function millions of times. And even if it was a recursive function with that property, I still wouldn't use your second method for the maintainability aspects you already brought up.

Edit: For arguments sake, I actually went and benchmarked this, and bar() ended up slower by 0.1s over one million calls. Which means performance wise, you still have a reason to use the cleaner version.

Matthew Scharley
+1  A: 

As monoxide said, there's no significant performance difference.

However, I'd avoid using global if at all possible; it's a bad road to go down and you'll end up with spaghetti. Use a static class; it'll keep things much better organized.

dirtside
While I agree with the first part, I don't see much benefit of using a static class. Globals should be avoided in all its forms.
troelskn
A: 

In case you don't know, you can do the following:

function foo() {
    global $fu, $bah;
    if (something()) {
        $fu->doSomething();
    } else {
        $bah->doSomething();
    }
}

You can put both of the globals in the same line. Might even make it faster :)

Darryl Hein
A: 

Global variables are generally considered very bad style. I would claim that whenever you need to use the global keyword, or a static class property (And thus, including the infamous Singleton), you should seriously reconsider what you're doing. It may be slightly more work to avoid globals, but it's a huge bonus to code maintainability. This particular example, might be better expressed with:

function foo($fu, $bah) {
  if (something()) {
    $fu->doSomething();
  } else {
    $bah->doSomething();
  }
}

If you don't like passing a lot of parameters around, you may use classes to encapsulate them, or perhaps it is a sign that you should factor your code differently.

troelskn
i agree: you don't want to go willy-nilly making things global variables - it's messy, doesn't scale well and doesn't play well with others (ie: when you combine your code with others'). BUT there are still good uses for it, and you can't just ignore it. Passing parameters each time does not work.
nickf