Entry
Is it faster to pass a global variable to a function as an argument?
Mar 3rd, 2000 10:59
Hamish Allan, Nathan Wallace, http://www.php.net/manual/functions.arguments.php3
There are three methods to access a global variable inside a function:
1. Having a (global) variable, setting it to "global" inside a function.
$language='EN';
function foo($param) {
global $language
...
}
2. Having a (global) variable, passing it with the function call to the
function.
$language='EN';
function poo($param, $language) {
...
}
3. Having a (global) variable, passing it by reference with the
function call to the function.
$language='EN';
function noo($param, &$language) {
...
}
The first and third methods are functionally equivalent, but the second
makes a copy (pass by value), which has two effects:
a. Space and time overheads are incurred on the copy.
b. Any changes to $language are local, so if we put the line:
$language=$param;
into each of our functions foo(), poo() and noo(), the behaviour is
as follows:
$language='EN';
foo('FR');
echo $language; // outputs FR
poo('DE', $language);
echo $language; // outputs FR
noo('ES', $language);
echo $language; // outputs ES