See what the global
keyword stands for here:
function aaa($b) {
$a = 30; # local variable, will be overwritten just in the next line
global $a, $c; # importing $a from the global scope - NULL
return $c = ($b + $a); # $c = (40 + NULL)
}
The manual at http://php.net/global reminds that a global variable influences the function if it is used inside there. That is not only for the first call but also for all subsequent calls.
This makes the function non-deterministic, so less useful code and you might - as you just did - get irritated by it.
An easy way out is: Instead of putting parametric values of that function into global variables, turn them into parameters:
function aaa($a, $b, &$c) {
return $c = ($b + $a);
}
echo aaa(30, 40, $c); //Output is 70
The code is not only much easier to read but also deterministic. It will always behave the same when called. That means less guessing.
This example still has the problem of returning a value by a parameter (by reference), however you might see as well that this is not really necessary any longer:
function aaa($a, $b) {
return ($b + $a);
}
echo $c = aaa(30, 40); //Output is 70
Lessons to take away:
- Do not use global variables inside functions - they only stand in your way.
- Reduce the number of parameters a function has (that are about all incomming values, so global counts as well).