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?
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.