Why PHP global variables cannot take effect. During actual operations, a newbie may encounter several times of depressing global variables that are invalid, next, let's take a look at the reasons why PHP's global variables cannot take effect and how to solve the problem.
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
However, in actual operations, the global variable will be invalidated several times in succession. next we will focus on the reasons why PHP global variables cannot take effect and the solution...