In depth understanding of global in PHP

  • 2021-07-13 04:32:01
  • OfStack

1. Implementation principle
In the function of PHP, global syntax is quite common. Everyone knows that after global has an external variable in the function, this variable can be used in this function, but many netizens don't know what implementation principle this is. Now, in the last example, you can see it by looking at it:


$globalStr = '.net'; function globalTest(){  global $globalStr;  $globalStr = 'jb51'.$globalStr;  unset($globalStr); } globalTest(); echo $globalStr; // Input : ofstack.com

From this example, it can be seen that global passes a reference by adding a variable. With this understanding, the output of the following code is not difficult to understand.

2. The role of global in php


global $var1,$var2;

It is the reference of the same name of the external variable, and the scope of the variable itself is still in the function body. By changing the values of these variables, the external variables with the same name will naturally change. But 1 denier was used & The variable will no longer be a reference of the same name.

<?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.

<?
$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. Take a step forward and look at the following code.

<?php 
$var1 = 1;   
$var2 = 2;   
function test_global()   
{   
    global $var1,$var2;   
    $var1=&$var2;   
    $var1=7;   
}
test_global();   
echo $var1;   
echo $var2;
?>

The results are 1 and 7. Because $var1 in the function has the same reference as $var2. Therefore, the value of $var1 is changed, and the night value of $var2 is changed.


Related articles: