I have a function that uses lots of global vars and arrays - e.g.
$a=1;
$b[0]=\'a\';
$b[1]=\'b\';
$c=\'Hello\';
function foo() {
echo \"$a
$b[0]
Since in PHP you do not have to declare variables before they are used, the following code is ambiguous as to what variable the function is referring to.
$a = 'ten';
function foo($a) {
echo($a);
}
foo(10); // Outputs: 10
PHP removes the ambiguity by assuming that all variables in the scope of a function are local, unless they are declared in the function to come from the global scope by using the global
keyword.
$a = 10;
function foo($b) {
global $a;
echo($a);
}
foo('ten'); // Outputs: 10
In general the use of global variables is discouraged since it introduces tight-coupling between your objects, decreases the readability and locality of code, pollutes the global namespace and increases the mental-load on developers having to remember how many/what global variables they have.