Global is a special command in PHP, you call him a super global variable, let me introduce today I am using global to define the overall learning notes
is not accustomed to the variable scope in PHP, PHP function variables and the global is completely isolated, that is, cannot access each other.
such as the following:
The code is as follows:
$test = 123; ABC (); Nothing here output, because access is not $test variable function abc () { echo ($test);} $test = 123;ABC (); Nothing here output, because access is not $test variable function abc () { echo ($test);}
If you want to access external variables inside a function, you need this:
The code is as follows:
$test = 123; ABC (); Output 123function ABC () { global $test; Echo ($test);} $test = 123;ABC (); Output 123function ABC () { global $test; Echo ($test);}
But what if we define global variables in the function, like this:
The code is as follows:
Function abc () { global $test; $test = 123;} ABC (); Echo ($test); Output 123function ABC () {global $test; $test = 123;} ABC (); Echo ($test);
Output 123
In this way, we can externally access the variables defined inside the function
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 (including variables within the import file of include and require) by default!
Explanation: The internal test_global of the a.php file is a defined third-party function that imports $ A in the global global variable of $ A in the b.php file with include, so $ A is limited to the Test_global local function, so the b.php file is within the $ The scope of a is within the test_global, not the whole a.php ....
Solution:
1. Punch out the local function
a.php file
The code is as follows:
<?phpfunction Test_global () { Test (); } Include ' b.php '; Move the include from the local Test_global function to $ A = 0; Test_global (); Echo $a;? >//b.php file <?phpfunction Test () { global $a; $a = 1;}? >
2. Excellent access to the viewer
The code is as follows:
a.php file
<?phpinclude ' b.php '; $a = 0; Set_global ($a); echo $a;? >//b.php file <?phpfunction set_global (& $var) {$var = 1;}?