相同点:
1、在函数内部使用函数体外声明的变量
$a = 1; function test1() { echo $a; } function test2() { global $a; echo $a; } function test3() { echo $GLOBALS['a']; } test1(); //Notice: Undefined variable: a test2(); //1 test3(); //1
2、在函数体外声明没有意义,函数内无法使用
global $a; $a = 1; function test1() { echo $a; } $GLOBALS['b'] = 2; function test2() { echo $b; } test1(); //Notice: Undefined variable: a test2(); //Notice: Undefined variable: b
区别:
global是引用,$GLOBALS直接就是变量本身
$a = 1; $b = 2; function test2() { global $a; echo $a; unset($a); } function test3() { echo $GLOBALS['b']; unset($GLOBALS['b']); } test2(); //1 echo $a; //1 test3(); //1 echo $b; //Notice: Undefined variable: b