1. All variables
A global variable, also known as an external variable, is defined outside the function and is scoped to the end of the program file, starting at the definition of the variable. Unlike other programming languages, global variables are not automatically set to be available. In PHP, because a function can be treated as a separate program fragment, the local variable overrides the visibility of the global variable, so the global variable cannot be called directly in the function. To use global variables in a function, you must define the target variable with the global keyword to tell the function body that this variable is a global variable. As shown below:
<?php
$one = 200;
$two = 100;
Function Demo () {
echo "Operation result:". ($one + $two). " <br> "; The equivalent of a new declaration within the function and does not have an initial value of two variables, the result output: 0
Global $one, $two;
echo "Operation result is:". ($one + $two). " <br> "; Using a global variable declared outside the function, output: 300
}
Using global variables in a function in addition to using the keyword Global, the second method of accessing variables globally is to use a special PHP custom $globals array. The previous example could be written using $globals instead of global. As shown below:
<?php
$one = 200;
$two = 100;
Function Demo () {
$GLOBALS [' one '] = $GLOBALS [' one '] + $GLOBALS [' one '];
}
Demo ();
Echo $two; Output 300, indicating that global variables are accessed to re-assigned values
In the $globals array, each variable is an element, the key name corresponds to the variable name, and the value corresponds to the contents of the variable. $GLOBALS exists globally because $globals is a super global variable.
function Application of PHP