Global & never understood how it works

Source: Internet
Author: User
Global & amp; has never understood how it works $ var1 & nbsp ;=& nbsp; 1; $ var2 & nbsp ;=& nbsp; 2; function & nbsp; test () {global & nbsp; $ var1, $ var2; & nbsp; // & nbsp; $ var1 & nbsp ;=& nbsp; 3; /global & never understood how it works

$ Var1 = 1;
$ Var2 = 2;
Function test (){
Global $ var1, $ var2 ;//
$ Var1 = 3; // $ var1 re-assigned and no return
}
Test ();
Echo $ var1; // why is it 3


$ Var1 = 1;
$ Var2 = 2;
Function test (){
Global $ var1, $ var2;
$ Var1 = & var2;
}
Test ();
Echo $ var1 // 1 cannot be understood


$ Var1 = 1;
$ Var2 = 2;
Function test_global ()
{
Global $ var1, $ var2;
$ Var1 = & $ var2;
$ Var1 = 7;
}
Test_global ();
Echo $ var1;
Echo $ var2; // The result is 1 and 7

------ Solution --------------------
No parameters are passed in the three functions of the landlord.
The role of global is here.
When you do not need to pass the parameter in, you need to use this variable again. Global
------ Solution --------------------
Thank you. Next, let's talk about the role of "&" $ var1 = & var2. how can we understand it?
------ Solution --------------------
$ Var1 = 1;
$ Var2 = 2;
Function test (){
Global $ var1, $ var2;
$ Var1 = & var2;
}
Test ();
Echo $ var1 // 1 cannot be understood
The $ var1 = & var2; $ var1 in the test () function is only a local variable in the function and does not belong to a global variable. If $ var1 is printed in test (), the result $ var1 = 2 is displayed;
------ Solution --------------------
$ Var1 = 1;
$ Var2 = 2;
Function test_global ()
{
Global $ var1, $ var2;
$ Var1 = & $ var2;
$ Var1 = 7;
}
Test_global ();
Echo $ var1;
Echo $ var2; // The result is 1 and 7

Let's look at this. Similarly, $ var1 is still a local variable. However, in test (), $ var1 = & $ var2; the code points the value of $ var1 to the memory address corresponding to the pointer of $ var2 (as AA ). In this case, $ var1 = 7, that is, change AA to 7.
PHP reference, hope to help you understand.

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.