First let’s look at a piece of code
<?php $a = 1 ; /* global scope */ function Test () { echo $a ; /* reference to local scope variable */ } Test (); ?>
This script will not have any output, because the echo statement references a local version of the variable $a, and within this scope, it has not been assigned a value. You may notice that PHP's global variables are a little different from C language. In C language, global variables automatically take effect in functions unless overridden by local variables. This may cause some problems, someone may accidentally change a global variable. Global variables in php must be declared global when used in functions.
global keyword
First, an example of using global, the code is as follows:
<?php $a = 1 ; $b = 2 ; function Sum () { global $a , $b ; $b = $a + $b ; } Sum (); echo $b ; ?>
The output of the above script will be "3". After global variables $a and $b are declared in a function, all references to either variable will point to its global version. PHP has no limit on the maximum number of global variables that a function can declare.
The second way to access variables in the global scope is to use a special PHP custom $GLOBALS array. The previous example can be written as:
Example #2 Use $GLOBALS instead of global, the code is as follows:
<?php $a = 1 ; $b = 2 ; function Sum () { $GLOBALS [ 'b' ] = $GLOBALS [ 'a' ] + $GLOBALS [ 'b' ]; } Sum (); echo $b ; ?>
$GLOBALS is an associative array, each variable is an element, and the key name corresponds to Variable name, the value corresponds to the content of the variable. The reason $GLOBALS exists in the global scope is because $GLOBALS is a superglobal variable. The following example shows the use of superglobal variables:
Example #3 Example demonstrating superglobal variables and scope
<?php function test_global () { // 大多数的预定义变量并不 "super",它们需要用 'global' 关键字来使它们在函数的本地区域中有效。 global $HTTP_POST_VARS ; echo $HTTP_POST_VARS [ 'name' ]; // Superglobals 在任何范围内都有效,它们并不需要 'global' 声明。Superglobals 是在 PHP 4.1.0 引入的。 echo $_POST [ 'name' ]; } ?>
The above is the detailed content of global keyword and $GLOBALS usage in php. For more information, please follow other related articles on the PHP Chinese website!