The scope of a variable is the context in which it is defined (that is, the scope it takes effect). Most PHP variables have a single range. This separate scope span also contains the files introduced by include and require.
For example:
The code is as follows |
Copy Code |
$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 scope is introduced. Any variables that are used inside the function will be limited to the local function in the default context. For example:
The code is as follows |
Copy Code |
$a = 1; /* Global scope */ function Test () { echo $a; /* Reference to local scope variable */ } Test (); ?> |
This script does not have any output, because the Echo statement refers to a local version of the variable $a, and within that range, it is not assigned a value. You may notice that the global variables in PHP are a little different from the C language, and in C, global variables are automatically applied in functions unless overridden by local variables. This can cause some problems, and some people may accidentally change a global variable. In PHP, global variables must be declared as globals when used in functions.
Global keyword
First, an example of using global:
Example #1 Use Global
The code is as follows |
Copy Code |
$a = 1; $b = 2; function Sum () { Global $a, $b; $b = $a + $b; } Sum (); Echo $b; ?> |
The output of 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 a function can declare.
The second way to access variables globally is to customize $GLOBALS arrays with special PHP. The previous example can be written as:
Example #2 use $GLOBALS instead of global
The code is as follows |
Copy Code |
$a = 1; $b = 2; function Sum () { $GLOBALS [' b '] = $GLOBALS [' a '] + $GLOBALS [' B ']; } Sum (); Echo $b; ?> |
1 2 3
http://www.bkjia.com/PHPjc/444672.html www.bkjia.com true http://www.bkjia.com/PHPjc/444672.html techarticle the scope of a variable is the context in which it is defined (that is, the scope it takes effect). Most PHP variables have a single range. This separate span also contains the incl ...