[Previous] [Contents] [Next]

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.

The global variable declaration can be a trap.

In some other languages, global variables are usually declared global outside the functions and then used in the functions.

In PHP, it's the opposite: to use a global variable inside a function, declare the variable as global inside the function.

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.

[Previous] [Contents] [Next]