This article introduces the global method of global variables in PHP in detail. if you need to know how to use global functions, refer to this article. the scope of a variable is the context defined by it (that is, its effective range ). most of the PHP variables are only one... this article introduces the global method of global variables in PHP in detail. if you need to know how to use global functions, refer to this article.
The scope of a variable is the context defined by it (that is, its effective range ). most PHP variables only have a single range. this independent range span also contains the files introduced by include and require.
The instance code is as follows:
Here the variable $ a will include file B. takes effect in inc. however, in user-defined functions, a local function range will be introduced. by default, any variable used in the function will be restricted within the range of a local function. for example:
The instance code is as follows:
This script does not have any output, because the echo statement references a local version of variable $ a and is not assigned a value within this range. you may notice that the global variables in PHP are a little different from those in C language. in C language, global variables automatically take effect in functions unless they are overwritten by local variables. this may cause some problems. some may accidentally change a global variable. global variables in PHP must be declared as global when used in functions.
Today we have encountered the problem that php global variables do not work. First, let's use the following simple code:
The instance code is as follows:
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:
The instance code is as follows:
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:
// A. php file
The instance code is as follows:
// B. php file
Why is the output 0 ?!!
In user-defined functions, a local function range will be 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
The instance code is as follows:
// A. php file
// B. php file
2. excellent accessors
The instance code is as follows:
// A. php file
// B. php file
Article URL:
Reprint ^ at will, but please attach the tutorial address.