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 PHP is 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 $GLOBALS superglobal?
我們將看到如何使用$ GLOBALS superglobal訪問全局定義的變量?
PHP代碼演示$ GLOBALS示例 (PHP code to demonstrate example of $GLOBALS)
<?php
//global variable
$name = 'my name is sam';
//function
function sayName() {
echo $GLOBALS['name'];
}
//calling the function
sayName();
?>
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 variables
function add2Numbers() {
$GLOBALS['sum'] = $GLOBALS['num1'] + $GLOBALS['num2'];
}
//calling function
add2Numbers();
//printing sum using global variable
echo $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中存在的變量,因此,也可以從函數外部對其進行訪問。
翻譯自: https://www.includehelp.com/php/$GLOBALS-super-global-variable-with-example.aspx
php globals