PHP’s global variables are a little different from C language. In C language, global variables automatically take effect in functions unless covered by local variables. This can cause problems, as someone might carelessly mutate a global variable. Global variables in PHP must be declared as global using global when used in functions.
1. Comparison with examples
Example 1:
The code is as follows
代码如下 |
复制代码 |
$var1 = 1;
function test(){
unset($GLOBALS['var1']);
}
test();
echo $var1;
?> |
|
Copy code
|
$var1 = 1;
function test(){
代码如下 |
复制代码 |
$var1 = 1;
function test(){
global $var1;
unset($var1);
}
test();
echo $var1;
?> |
unset($GLOBALS['var1']);
}
test();
echo $var1;
?>
Because $var1 was deleted, nothing is printed.
Example 2:
The code is as follows
|
Copy code
|
$var1 = 1; |
function test(){
global $var1;
unset($var1);
}
test();
echo $var1;
?>
Accidentally printed 1. It proves that only the alias reference is deleted, and its value has not been changed in any way.
2. Explanation
Global $var is actually &$GLOBALS['var'], which is just an alias for calling external variables.
$var1 and $GLOBALS['var1'] in the above code refer to the same variable, not two different variables.
PHP’s global variables are a little different from those in C language. In C language, global variables automatically take effect in functions unless covered by local variables. This can cause problems, as someone might carelessly mutate a global variable. Global variables in PHP must be declared as global using global when used in functions.
The function of PHP's Global variable is to define global variables, but this global variable does not apply to the entire website, but to the current page, including all files in include or require.
3. Conclusion
1.$GLOBALS['var'] is the external global variable itself
http://www.bkjia.com/PHPjc/632199.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632199.htmlTechArticlePHP’s global variables are a little different from C language. In C language, global variables automatically take effect in functions unless covered by local variables. This may cause some problems and some people may be confused...
|