Lets say you have an program like this:
$info = array(
'username'=>'jeff',
'password'=>'kay'
);
function authenticate($user, $pass) {
if($user == $info['username'] && $pass == $info['password']) {
return true;
}
return false;
}
This code won’t work because the $info array isn’t in authenticate()‘s scope. You would have to pass $info as a parameter of authenticate() like so:
function authenticate($info, $user, $pass) { // ... }
This feels wrong to me.
I could certainly add global $info; inside of authenticate but that feels even more wrong. What is best practice for structuring a PHP program to avoid scope issues like this? You don’t see functions requiring you to pass in the ‘global’ object in modern code it seems like. How do I avoid unnecessary function arguments?
Most people do not notice, but this is actually a very good question.
Many other languages (especially functional ones) have lexical scope. With PHP 5.3 lambdas you get that capability, but only within lambdas. Let me show you what I mean:
With the
useyou can import variables from the outer scope, but it only works for anonymous functions. It really depends on what kind of style and framework you’re coding in/with.If you don’t want to define these inline (since you must assign them to variables, which is not so nice), I’d suggest you go with your instincts, so pass
$infointoauthenticateor make$infoan instance variable of the class thatauthenticatebelongs to.