The difference and usage between global and $GLOBALS['']

【Foreword】

   There is a global keyword in the variable scope of PHP

 

【effect】

   It is used to access global variables within the function and call the global variables defined outside the function within the function. We need to add the global keyword before the variables in the function

 

【Case】

<?php  
$x=5;  
$y=10;  
function myTest(){  
    overall $x,$y;  
    $y=$x+$y;  
}  
myTest();  
echo $y; // output 15  
?>  

   PHP stores all global variables in an array called $GLOBALS[index]. index holds the name of the variable. This array can be accessed inside a function or used directly to update global variables.

   The above example can be written as:

<?php  
$x=5;  
$y=10;   
function myTest(){  
    $ GLOBALS ['y'] = $ GLOBALS ['x'] + $ GLOBALS ['y'];  
}   
myTest();  
echo $y;  
?>  

 

【Compared】

   Many people think that global and $GLOBALS[] are just differences in the way they are written, but they are not.

   According to the official explanation:

      $GLOBALS['var'] is the external global variable $var itself, PHP stores all global variables in the $GLOBALS[index] array;

      global $var is a same-named or aliased reference to an external $var

 

 

 

Reference URL: http://blog.csdn.net/Yeoman92/article/details/52681376

 What does the & in &$var1 in php mean? http://blog.csdn.net/qq_25551295/article/details/48807965

 

 

 

.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326082458&siteId=291194637