相同點:
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