Home  >  Article  >  Backend Development  >  Analysis of the difference between global variables global and $GLOBALS[] in PHP_PHP Tutorial

Analysis of the difference between global variables global and $GLOBALS[] in PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:17:11836browse

< ?php $var1 = 1; function test(){
unset($GLOBALS['var1']);
}

test(); echo $var1; ?> Because $var1 was deleted, nothing is printed.

Example 2:



Copy code

The code is as follows:


$var1 = 1;
function test(){
global $var1;
unset($var1);
} test(); echo $var1; ?>
Unexpectedly 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 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.
PHP’s Global variable is used 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
2.global $var is the reference or pointer of the same name of the external $var .

http://www.bkjia.com/PHPjc/325770.html

www.bkjia.com

true
http: //www.bkjia.com/PHPjc/325770.html

TechArticle

1. Comparative Example 1: Copy the code as follows: ?php $var1 = 1; function test(){ unset($GLOBALS['var1']); } test(); echo $var1; ? Because $var1 was deleted, something...

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn