In PHP, global is different from ¥ GLOBALS [] to develop a PHP program. it is inevitable to use global data. global variables are one of them. Of course this is quite controversial. many people suggest disabling global variables. Improper use may cause poor program readability! The structure is messy and debugging is even more confusing, but it is undeniable that it is convenient. This is why php uses the global variable !... What is the difference between global and ¥ GLOBALS [] in PHP today?
Develop a PHP program and use global data inevitably.
Global variablesThis is one of them. of course, this idea is quite controversial. many people still suggest disabling global variables. Improper use causes poor program readability! The structure is messy and debugging is even more difficult, but it is undeniable that it is convenient. This is why php usesGlobalWhy !...
Today we have encountered the problem that php global variables do not work.
First, a simple code:
The output in the above code is 0, because the $ a variable in the Test function is set as a local variable by default, and the $ a scope is in the Test. modify the code as follows:
05 |
global$a;// Declare that the $ a variable used in the Test function is a global variable. |
After the $ a variable used in the Test function is declared as a global variable, the output of $ a is 1.
The above example is just a basic knowledge of global variables. let's look at the complex points:
04 |
function Test_Global() |
20 |
global$a;// Declare that the $ a variable used in the Sum function is a global variable. |
Why is the output 0 ?!!
In a user-defined function, a local function range is introduced.Any variables used in the function will be limited to the local function scope by default (including the variables in the include and require imported files )!
Explanation: Test_Global in the. php file is a defined third-party function. this function imports the global variables of $ A in the B. php file using include.$ A is restricted to the range of Test_Global local functions.Therefore, $ a in the B. php file takes effect in Test_Global instead of in A. php ....
Solution: 1. rush out of the local function
04 |
function Test_Global() |
08 |
include 'B.php'; // Remove include from the local Test_Global function |
2. excellent accessors
11 |
function Set_Global(&$var) |