This article mainly introduces a deep understanding of global in PHP, describes the implementation principle and function of global in a concise language, and provides sample code. For more information, see
I. implementation principle
In PHP functions, the global syntax is quite common. everyone knows that once an external variable is global in the function, this variable can be used in this function, however, many netizens do not know how this works. Now, in the previous example, we can see it at a glance:
The code is as follows:
$ GlobalStr = '. net ';
Function globalTest (){
Global $ globalStr;
$ GlobalStr = 'jb51 '. $ globalStr;
Unset ($ globalStr );
}
GlobalTest ();
Echo $ globalStr; // input: bitsCN.com
From this example, a global variable is passed as a reference. In this way, the output results of the following code are not difficult to understand.
II. Role of global in php
The code is as follows:
Global $ var1, $ var2;
Is the reference of an external variable with the same name, and the scope of the variable is still in the function. When you change the values of these variables, the external variables with the same name also change. However, once & is used, the variable will no longer be referenced with the same name.
The code is as follows:
<? Php
$ Var1 = 1;
$ Var2 = 2;
Function test ()
{
Global $ var1, $ var2; // The scope of action is in the function body.
$ Var1 = 3;
}
Test ();
Echo $ var1;
?>
The result is 3. Because it is a reference with the same name.
The code is as follows:
<?
$ Var1 = 1;
$ Var2 = 2;
Function test ()
{
Global $ var1, $ var2;
$ Var1 = & var2;
}
Test ();
Echo $ var1
?>
The result is 1. Because $ var1 in the function has the same reference as $ var2 after being assigned a value. Let's look at the following code.
The code is as follows:
<? Php
$ 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. Because $ var1 in the function has the same reference as $ var2. Therefore, the value of $ var1 is changed, and the value of $ var2 is changed.