Home  >  Article  >  Backend Development  >  The difference between global variables global and $GLOBALS[] in PHP_PHP Tutorial

The difference between global variables global and $GLOBALS[] in PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:55:55857browse

PHP’s global variables are a little different from C language. In C language, global variables automatically take effect in functions unless covered by local variables. This can cause problems, as someone might carelessly mutate a global variable. Global variables in PHP must be declared as global using global when used in functions.

1. Comparison with examples
Example 1:

The code is as follows
 代码如下 复制代码
$var1 = 1;
function test(){
unset($GLOBALS['var1']);
}
test();
echo $var1;
?>  
Copy code


$var1 = 1;

function test(){
代码如下 复制代码
$var1 = 1;
function test(){
global $var1;
unset($var1);
}
test();
echo $var1;
?>
                                                                unset($GLOBALS['var1']); } 

test();
echo $var1;

?>





Because $var1 was deleted, nothing is printed.

Example 2:

function test(){
The code is as follows
Copy code
$var1 = 1;
global $var1;

              unset($var1);                                             } 

test();

echo $var1;
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn