php globals
PHP $全球 (PHP $GLOBALS)
PHP $GLOBALS is the only superglobal that does not begin with an underscore (_). It is an array that stores all the global scope variables.
PHP $ GLOBALS是唯一不以下划线( _ )开头的超全局变量。 它是一个存储所有全局范围变量的数组。
$GLOBALS in PHPis used to access all global variables (variables from global scope) i.e. the variable that can be accessed from any scope in a PHP script.
PHP中的$ GLOBALS用于访问所有全局变量(来自全局范围的变量),即可以从PHP脚本中的任何范围访问的变量。
Example of $GLOBALS in PHP
PHP中的$ GLOBALS的示例
We will see how to access a variable defined globally with the$GLOBALSsuperglobal?
我们将看到如何使用$ GLOBALSsuperglobal访问全局定义的变量?
PHP代码演示$ GLOBALS示例 (PHP code to demonstrate example of $GLOBALS)
<?php//global variable$name = 'my name is sam';//functionfunction sayName() {echo $GLOBALS['name'];}//calling the functionsayName();?>
Output
输出量
my name is sam
By defining the $name variable it automatically is stored in the superglobal variable $GLOBALS array. This explains why we can access it in the sayName() function without defining it in the function.
通过定义$ name变量,它会自动存储在超全局变量$ GLOBALS数组中。 这就解释了为什么我们可以在sayName()函数中访问它而无需在函数中定义它的原因。
PHP代码通过使用$ GLOBALS访问全局变量来查找两个数字的和 (PHP code to find sum of two numbers by accessing global variables using $GLOBALS)
<?php//global variables$num1 = 36;$num2 = 24;//function to access global variablesfunction add2Numbers() {$GLOBALS['sum'] = $GLOBALS['num1'] + $GLOBALS['num2'];}//calling functionadd2Numbers();//printing sum using global variableecho $sum;?>
Output
输出量
60
In the code above, num1 and num2 are global variables so we are accessing them using $GLOBALS, and sum is a variable present within$GLOBALS, thus, it is accessible from outside the function also.
在上面的代码中, num1和num2是全局变量,因此我们使用$ GLOBALS访问它们,并且sum是$ GLOBALS中存在的变量,因此,也可以从函数外部对其进行访问。
翻译自: /php/$GLOBALS-super-global-variable-with-example.aspx
php globals