Home >Backend Development >PHP Tutorial >The difference between PHP global variables global and $GLOBALS[]

The difference between PHP global variables global and $GLOBALS[]

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-25 09:05:141018browse
  1. $var1 = 1;
  2. function test(){
  3. unset($GLOBALS['var1']);
  4. }
  5. test();
  6. echo $var1;
  7. ?>
Copy code

Since $var1 is deleted, nothing is printed.

Example 2:

  1. $var1 = 1;
  2. function test(){
  3. global $var1;
  4. unset($var1);
  5. }
  6. test();
  7. echo $var1;
  8. ?>
Copy code

Accidentally printed 1. It proves that only the alias reference is deleted, and its value is not 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. 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. Summary 1.$GLOBALS['var'] is the external global variable itself 2.global $var is a reference or pointer of the same name as an external $var.



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