We are not used to the variable scope in PHP. Function variables in PHP are completely isolated from the global ones, that is, they cannot access each other.
For example:
Copytext
| The code is as follows: |
Copy code |
|
$ Test = 123;
Abc (); // nothing is output here, because the $ test variable cannot be accessed.
Function abc (){
Echo ($ test );
} $ Test = 123;
Abc (); // nothing is output here, because the $ test variable cannot be accessed.
Function abc (){
Echo ($ test ); |
} If you want to access external variables within the function, you need:
Copytext
| The code is as follows: |
Copy code |
|
$ Test = 123;
Abc (); // output 123
Function abc (){
Global $ test;
Echo ($ test );
} $ Test = 123;
Abc (); // output 123
Function abc (){
Global $ test;
Echo ($ test );
} |
But what if we define global variables in the function, as shown below:
Copytext
| The code is as follows: |
Copy code |
Function abc (){
Global $ test;
$ Test = 123;
}
Abc ();
Echo ($ test); // output 123 function abc (){
Global $ test;
$ Test = 123;
}
Abc ();
Echo ($ test ); |
// Output 123. In this way, we can access the variables defined in the function externally.
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, which is imported into B using include. the global variable of $ a in the PHP file, so $ a is restricted to the range of local functions of Test_Global, so B. $ a in the PHP file takes effect in Test_Global, instead of. php ....
Solution:
1. Rush out of the local function
& Nbsp; // A. php file
| The code is as follows: |
Copy code |
|
<? Php
Function Test_Global ()
{& Nbsp;
Test (); & nbsp;
} & Nbsp;
Include 'B. Php'; & nbsp; // Remove include from the local Test_Global function
$ A = 0;
Test_Global ();
Echo $;
?> & Nbsp;
// B. php file
<? Php
Function Test ()
{
Global $;
$ A = 1;
}
?> |
2. Excellent accessors
| The code is as follows: |
Copy code |
|
// A. php file
<? Php
Include 'B. Php'; & nbsp;
$ A = 0;
Set_Global ($ );
Echo $;
?> & Nbsp;
// B. php file
<? Php
Function Set_Global (& $ var)
{
$ Var = 1;
}
?> |