Php 简明教程
PHP - $GLOBALS
$GLOBALS 是 PHP 中的 " superglobal " 或 " automatic global " 变量之一。它在脚本的各个范围中均可用。无需在函数或方法中访问它时执行 " global $variable; "。
$GLOBALS is one of the "superglobal" or "automatic global" variables in PHP. It is available in all scopes throughout a script. There is no need to do "global $variable;" to access it within functions or methods.
$GLOBALS 是对所有全局定义的变量的引用的关联数组。变量的名称形成键,其内容是关联数组的值。
$GLOBALS is an associative array of references to all globally defined variables. The names of variables form keys and their contents are the values of an associative array.
Example
此示例显示 $GLOBALS 数组包含全局变量的名称和内容−
This example shows $GLOBALS array containing the name and contents of global variables −
<?php
$var1="Hello";
$var2=100;
$var3=array(1,2,3);
echo $GLOBALS["var1"] . "\n";
echo $GLOBALS["var2"] . "\n";
echo implode($GLOBALS["var3"]) . "\n";
?>
它将生成以下 output −
It will produce the following output −
Hello
100
123
Example
在以下示例中, $var1 在全局命名空间和函数内部的局部变量中进行定义。全局变量从 $GLOBALS 数组中提取。
In the following example, $var1 is defined in the global namespace as well as a local variable inside the function. The global variable is extracted from the $GLOBALS array.
<?php
function myfunction() {
$var1="Hello PHP";
echo "var1 in global namespace: " . $GLOBALS['var1']. "\n";
echo "var1 as local variable: ". $var1;
}
$var1="Hello World";
myfunction();
?>
它将生成以下 output −
It will produce the following output −
var1 in global namespace: Hello World
var1 as local variable: Hello PHP
Example
在 PHP 8.1.0 版本之前,全局变量可以通过 $GLOBALS 数组的副本进行修改。
Prior to PHP version 8.1.0, global variables could be modified by a copy of $GLOBALS array.
<?php
$a = 1;
$globals = $GLOBALS;
$globals['a'] = 2;
var_dump($a);
?>
它将生成以下 output −
It will produce the following output −
int(1)
在此处, $globals 是 $GLOBALS 超全局变量的副本。修改副本中键为 "a" 的元素值至 2,实际上会更改 $a 的值。
Here, $globals is a copy of the $GLOBALS superglobal. Changing an element in the copy, with its key as "a" to 2, actually changes the value of $a.
它将生成以下 output −
It will produce the following output −
int(2)
Example
在 PHP 8.1.0 及更高版本中,$GLOBALS 是全局符号表的只读副本。也就是说,全局变量无法通过其副本进行修改。与上述操作相同的操作不会将 $a 更改为 2。
As of PHP 8.1.0, $GLOBALS is a read-only copy of the global symbol table. That is, global variables cannot be modified via their copy. The same operation as above won’t change $a to 2.
<?php
$a = 1;
$globals = $GLOBALS;
$globals['a'] = 2;
var_dump($a);
?>
它将生成以下 output −
It will produce the following output −
int(1)