预定义变量
在线手册:中文 英文
PHP手册

$GLOBALS

$GLOBALS引用全局作用域中可用的全部变量

说明

一个包含了全部变量的全局组合数组。变量的名字就是数组的键。

范例

Example #1 $GLOBALS 范例

<?php
function test() {
    
$foo "local variable";

    echo 
'$foo in global scope: ' $GLOBALS["foo"] . "\n";
    echo 
'$foo in current scope: ' $foo "\n";
}

$foo "Example content";
test();
?>

以上例程的输出类似于:

$foo in global scope: Example content
$foo in current scope: local variable

注释

Note:

“Superglobal”也称为自动化的全局变量。 这就表示其在脚本的所有作用域中都是可用的。不需要在函数或方法中用 global $variable; 来访问它。

Note: 变量可用性

与所有其他超全局变量不同,$GLOBALS在PHP中总是可用的。


预定义变量
在线手册:中文 英文
PHP手册
PHP手册 - N: 引用全局作用域中可用的全部变量

用户评论:

therandshow at gmail dot com (29-Jun-2011 02:32)

As of PHP 5.4 $GLOBALS is now initialized just-in-time. This means there now is an advantage to not use the $GLOBALS variable as you can avoid the overhead of initializing it. How much of an advantage that is I'm not sure, but I've never liked $GLOBALS much anyways.

williams at 3cisd dot com (28-Jul-2009 11:53)

Better yet, use print_r.  While var_dump does detect the recursion that var_export fails on, it seems to recurse one level first for my setup.  So var_dump ends up printing all globals twice, but print_r prints them only once since it detects the recursion right away.  Serialize seems to not detect the recursion at all either, similar to var_export.

David (14-Aug-2008 01:47)

Though you can use var_dump to output the value of $GLOBALS.

ravenswd at yahoo dot com (12-Aug-2008 09:02)

Keep in mind that $GLOBALS is, itself, a global variable. So code like this won't work:

<?php
   
print '$GLOBALS = ' . var_export($GLOBALS, true) . "\n";
?>

This results in the error message: "Nesting level too deep - recursive dependency?"