Will $a = 1 and $b = 2 in the function? If so is this the best approach?Code:
$a = 1;
$b = 2;
function nekkidrage()
global $a, $b;
exit()
Printable View
Will $a = 1 and $b = 2 in the function? If so is this the best approach?Code:
$a = 1;
$b = 2;
function nekkidrage()
global $a, $b;
exit()
yes, they will be available to the function. this approach is perfectly fine. you could also use the $GLOBALS array, but I prefer the method you posted.
more on variable scopePHP Code:function sum(){
return $GLOBALS['a'] + $GLOBALS['b'];
}
I prefer not to use globals — for things which require global access, I use static variables in classes.
This approach gives you organisation: you can have a settings class, a database class, and so on.
A function to me should be self-contained (unlike a class method). It should be stateless and deterministic — the same input should always give the same output — unless it is specifically otherwise (such as a pseudo-random algorithm).
That's general advice, not just for PHP. Your approach is perfectly valid; I'm just offering another viewpoint.
Objects exist to provide state and so my opinion is that any function which requires state should be a class method.
Nice function name, by the way...