Difference between global and ¥globals[in PHP
To develop a PHP program, it is unavoidable to use the global data.
Global Variables are one of them, of course, this view is controversial, many people still recommend disabling global variables, improper use of the resulting program readability is poor! The structure is chaotic, the debugging is confused, but cannot deny his convenience, this is why PHP uses Global variables Globally why is it!...
Today, we encountered a problem where the PHP global variables did not work.
Let's start with a simple code:
The output in the above code is 0, because the $ A variable in the function body test is defaulted to a local variable, and the scope of the $a is within test. Modify the code as follows
05 |
global $a ; //申明函数体Test内使用的$a变量为global全局变量 |
Declare that the $ A variable used within the function body test is the global global variable, so that $ A has the overall effect, so the output is 1.
The above example is just the basic global variables knowledge, below we look at the complex point:
20 |
global $a ; //申明函数体Sum内使用的$a变量为global全局变量 |
Why is the output 0?!!
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 well-defined third-party function that imports $ A in the global global variable of $ A in the b.php file with include, so the $a is limited to the scope of the Test_global local function , So the $ A within the b.php file is within Test_global, not the whole a.php ....
Solution:
1. Punch out the local function
08 |
include 'B.php' ; //将include 从局部Test_Global函数中移出 |
2. Excellent access to the viewer
11 |
function Set_Global(& $var ) |