You already know that variables inside a function have their own scope and don't mix with variables outside the function: $value = 5; echo "At script level, \$value = ", $value, "<BR>"; local_scope(); echo "At script level again, \$value still = ", $value, "<BR>"; function local_scope() { $value = 1000000; echo "But in the function, \$value = ", $value, "<BR>"; } But what if you actually wanted to access the value of a script-level variable, called a global variable, inside a function? For example, if you set $value to 5 at the script level, you might try to access its value inside a function like this: $value = 5; function global_scope() { echo "\$value = ", $value, "<BR>"; } However, this won't work (although it will in some languages) because PHP wants to prevent unintentional conflict between global and local variables. If you want to access a global variable in a function, you have to explicitly say so. One way of doing this is with the global keyword, as you see in phpglobal.php, Example 4-9. Example 4-9. Using global scope data in functions, phpglobal.php<HTML> <HEAD> <TITLE> Using global and local scope </TITLE> </HEAD> <BODY> <H1> Using global and local scope </H1> <?php $value = 5; echo "At script level, \$value = ", $value, "<BR>"; local_scope(); global_scope(); echo "At script level again, \$value still = ", $value, "<BR>"; function local_scope() { $value = 1000000; echo "But in the function, \$value = ", $value, "<BR>"; } function global_scope() { global $value; echo "Using the global scope, \$value = ", $value, "<BR>"; } ?> </BODY> </HTML> After you indicate that you want access to the global value in $value, PHP gives it to you, as you can see in Figure 4-9. Figure 4-9. Using global and local scope.You can also access global data by using the special PHP-defined $GLOBALS array. Here's how you would do that in this example: function global_scope() { echo "Using the global scope, \$value = ", $GLOBALS["value"], "<BR>"; } |