For a newbie
However, in actual operations, we will encounter several times of depressing global variable invalidation. Next we will focus on the reasons why PHP global variables cannot take effect and the solutions.
1. PHP global variables cannot take effect error Reproduction
When using my simple framework and using functions defined by a third party in view (this function is relatively independent), the following is a simulation:
T1.php
- <?
- Run (); // Execute
- Function run (){
- Include 'func. php ';
- ShowGlobal ();
- }
- ?>
Func. php1
- <?
- $ Vars = 'I am global! ';
- Function showGlobal (){
- Global $ vars;
- Print ('use global variables: '. $ vars );
- }
- ?>
Very simple two files (the first time I found the problem, it was far more complex than this, after a layer-by-layer troubleshooting, I got the minimal problem to reproduce the environment), func. php is a defined third-party function that uses some global variables. If you put these two files together, run t1.php, $ vars in showGlobal cannot be displayed, but is global invalid?
2. Why does the PHP global variable fail to take effect?
After searching, it was found that some people have mentioned php.net for a long time and some people have explained it:
Originally, the run function of t1.php included func. in php, func. the $ vars variable in php is only available in run, while $ vars declared by global in showGlobal requires that the variable that belongs to t1.php is not a run function, so it is empty)
3. PHP global variables cannot take effect Solution
After knowing the cause, the solution is very simple. You can remove the include from the run. In this way, func. $ vars in php belongs to t1.php. You can also declare $ vars with global in run. In this way, you can declare $ vars that originally belonged to run as global (t1.php );
Although the problem can be simplified, it is still quite uncomfortable to use, because in my phpec framework, the include situation is quite common and it is impossible to move the view to the outer layer according to the need to include, when using global, I don't even want to know what global variables it uses when using third-party functions. Besides, if there are many hierarchies ....
Summary:
1) Minimize the number of levels and include files in functions.
2) Try not to use global variables