Analysis of the difference between global and $globals[in PHP _php techniques

Source: Internet
Author: User
A comparison of examples
Example one:
Copy Code code as follows:

<?php
$var 1 = 1;
function Test () {
unset ($GLOBALS [' var1 ']);
}
Test ();
echo $var 1;
?>

Because the $var1 was deleted, nothing was printed.
Case TWO:
Copy Code code as follows:

<?php
$var 1 = 1;
function Test () {
Global $var 1;
Unset ($var 1);
}
Test ();
echo $var 1;
?>

The 1 was printed unexpectedly. The deletion is only an alias reference, and its own value has not been changed.

Second, explain
The global $var is actually & $GLOBALS [' var '], calling an alias for an external variable.
The $var1 and $globals[' var1 ' in the code above refer to the same variable, not two different variables.
PHP's global variables are a little different from the C language. In the C language, global variables are active in the function unless they are shadowed by local variables. This may cause some problems, and some people may inadvertently change a global variable. Global variables in PHP must be declared global when they are applied in a function.
PHP's global variable is defined as a global variable, but the global variable is not applied to the entire Web site, but is applied to the current page, including all files with include or require.

Third, the conclusion
1. $GLOBALS [' var '] is the external global variable itself
2.global $var is a reference or pointer with the same name as an external $var.

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.