For example:
The code is as follows |
Copy Code |
<?php $a = 1; Include ' B.inc '; ?> |
Here the variable $a will take effect in the include file B.inc. However, in a user-defined function, a local function range is introduced. Any variable that is used inside a function is limited by default to the scope of the local function. For example:
The code is as follows |
Copy Code |
<?php $a = 1; /* Global Scope * * function Test () { echo $a; /* Reference to local scope variable * * } Test (); ?> |
This script will not have any output because the Echo statement refers to a local version of the variable $a, and within that scope it is not assigned. You may notice that the global variable in PHP is a little bit different from the C language, in which the global variable takes effect automatically in the function unless overridden by a local variable. This can cause some problems, and some people may change a global variable accidentally. A global variable in PHP must be declared global when it is used in a function.
Global keyword
First, an example of using global:
Example #1 Use Global
The code is as follows |
Copy Code |
<?php $a = 1; $b = 2; function Sum () { Global $a, $b; $b = $a + $b; } Sum (); Echo $b; ?> |
The output from the above script will be "3". The global variable $a and $b are declared in the function, and all reference variables of any variable are pointed to the global variable. PHP has no restrictions on the maximum number of global variables that a function can declare.
The second way to access a variable globally is to use a special PHP custom $GLOBALS array. The preceding example can be written as:
Example #2 use $GLOBALS instead of global
The code is as follows |
Copy Code |
<?php $a = 1; $b = 2; function Sum () { $GLOBALS [' b '] = $GLOBALS [' a '] + $GLOBALS [' B ']; } Sum (); Echo $b; ?> |