Global variables
If you want to use the same variable everywhere in your code, including within functions, you can do so with the global statement. The global statement declares a variable within a function as being the same as the variable that is used outside of the function. Consider this example:
function doublevalue( )
{
global $temp;
$temp = $temp * 2;
}
$temp = 5;
doublevalue( );
echo "\$temp is: $temp";
Because $temp is declared inside the function as global, the variable $temp used in doublevalue( ) is a global variable that can be accessed outside the function. Because the variable $temp can be seen outside the function, the script prints:
$temp is: 10
A word of caution: avoid overuse of global as it makes for confusing code.
|
An alternative to using global is to return more than one variable from a function by creating and returning an array of values. A better approach is to pass parameters by reference instead of by value. We discuss the latter approach in the next section.