First, the realization principle
in the PHP function, the global syntax is more common, we must all know once in the function of global an external variable, this variable can be used in this function, but there are many users do not know what this is a principle of what to achieve. Now, in the last example, you'll see:
Copy Code code as follows:
$GLOBALSTR = '. NET ';
function Globaltest () {
Global $globalStr;
$globalStr = ' jb51 '. $globalStr;
Unset ($GLOBALSTR);
}
Globaltest ();
Echo $globalStr; Input: Jb51.net
This example shows that global has a variable that is equivalent to passing a reference in. In this way, the following code output is not difficult to understand.
second, the role of global in PHP
Copy Code code as follows:
is a reference to an external variable with the same name, and the scope of the variable itself is still inside the function. Changing the value of these variables, the external variable of the same name will naturally change. But once you use the ampersand, the variable will no longer be a reference of the same name.
Copy Code code as follows:
<?php
$var 1 = 1;
$var 2 = 2;
function test ()
{
Global $var 1, $var 2; The scope of the function in the body
$var 1 = 3;
}
Test ();
echo $var 1;
?>
The result is 3. Because it is a reference of the same name.
Copy Code code as follows:
?
$var 1 = 1;
$var 2 = 2;
function test ()
{
Global $var 1, $var 2;
$var 1 = &var2;
}
Test ();
echo $var 1
?>
The result is 1. Because the $var1 in the function has the same reference as the $VAR2 after it has been assigned. Look further at the code below.
Copy Code code as follows:
<?php
$var 1 = 1;
$var 2 = 2;
function Test_global ()
{
Global $var 1, $var 2;
$var 1=& $var 2;
$var 1=7;
}
Test_global ();
echo $var 1;
echo $var 2;
?>
The result is 1 and 7. Because the $var1 within the function has the same reference as the $VAR2. As a result, changes were made to the value of $VAR1, $var 2 programmed.