Differences between global variables and $ GLOBALS [] in PHP _ PHP Tutorial

Source: Internet
Author: User
Difference between global variables and $ GLOBALS [] in PHP. I. Example 1: Copy the code as follows :? Php $ var11; functiontest () {unset ($ GLOBALS [var1]);} test (); echo $ var1 ;? Because $ var1 is deleted, so what? 1. Comparison of examples
Example 1:

The code is as follows:


$ Var1 = 1;
Function test (){
Unset ($ GLOBALS ['var1']);
}
Test ();
Echo $ var1;
?>


Because $ var1 is deleted, nothing is printed.
Example 2:

The code is as follows:


$ Var1 = 1;
Function test (){
Global $ var1;
Unset ($ var1 );
}
Test ();
Echo $ var1;
?>


Accidentally printed 1. It indicates that only alias reference is deleted, and its value is not changed.

II. Explanation
Global $ var is actually an alias for calling an external variable & $ GLOBALS ['var.
$ Var1 and $ GLOBALS ['var1'] in the above code refer to the same variable, rather than two different variables.
The global variables of PHP are a little different from those of C. In C, global variables take effect in functions unless they are shrouded in local variables. This may cause some problems. some may carelessly change a global variable. Global variables in PHP must be declared as global in the function.
PHP's Global variable defines Global variables, but this Global variable is not applied to the entire website, but to the current page, including all files including include or require.

III. Conclusion
1. $ GLOBALS ['var'] is an external global variable.
2. global $ var is an external reference or pointer with the same name as $ var.

Example 1: The code is as follows :? Php $ var1 = 1; function test () {unset ($ GLOBALS ['var1']);} test (); echo $ var1 ;? Because $ var1 is deleted, so what is it...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.