Global is a global variable in php. This global is only a global variable on the page. For example, we can directly use the global declaration in the function to obtain the value of the variable.
Example
The Code is as follows: |
Copy code |
<? Php $ A = 12; Function fn () { Global $ a; // use the outer $ a variable. Do not use this method $ a as a local variable. $ A + = 12; }
Echo '$ a ='. $ a // output result ?> Output result: $ a = 24 |
Conclusion: global variables defined in the function body can be used in vitro. global variables defined in the function body cannot be used in the function body,
The Code is as follows: |
Copy code |
$ Glpbal $; $ A = 123; Function f () { Echo $ a; // error, } // Take a look at the following example. Function f () { Global $; $ A = 123; } F (); Echo $ a; // correct, which can be used |
The above example is just a basic knowledge of global variables. Let's look at the complex points:
The Code is as follows: |
Copy code |
// A. php file <? Php Function Test_Global () { Include 'B. php '; Test (); } $ A = 0; Test_Global (); Echo $; ?> // B. php file <? Php Function Test () { Global $ a; // declare that the $ a variable used in the Sum function is a global variable. $ A = 1; } ?> |
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, 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 Code is as follows: |
Copy code |
// A. php file <? Php Function Test_Global () { Test (); } Include 'B. php'; // remove include from the local Test_Global Function $ A = 0; Test_Global (); Echo $; ?> // B. php file <? Php Function Test () { Global $; $ A = 1; } ?> |
Global Problem Analysis:
Question: In config. inc. php defines some variables ($ a). In other files, the function external include ("config. inc. php "), the function needs to use these variables $ a internally. If no declaration is made, echo $ a cannot print anything. Therefore, we declare global $ a. But there are a lot of functions and many variables that cannot be repeatedly declared? Please advise if you have any good solutions.
Answer1: first define a constant in config. inc. php: define (constant name, constant value)
Then, in other places that need to be used, require 'config. inc. php ',
Then you can directly use this constant in this file.
Answer2: I also have a way to define an array, such as $ x [a], $ x, so that we only need to declare a global $ x.
Answer3: I tried your method. No.
Answer4: Modify your php. ini file.