Home >Backend Development >PHP Tutorial >Introduction to why PHP global variables cannot take effect_PHP tutorial
For a novice in actual operation
But in actual operation, he will encounter several depressing things that global variables are invalid. Let’s focus on PHP. Reasons why global variables cannot take effect and solutions.
1. PHP global variables cannot take effect and the error reappears
The problem occurs when using my simple framework and using the function defined by the original third party in the view (This function is relatively independent), simulate it below:
t1.php
func.php1
<ol class="dp-xml"><li class="alt"><span><span class="tag"><</span><span> ? </span></span></li><li><span>$</span><span class="attribute">vars</span><span> = </span><span class="attribute-value">'I am global!'</span><span>; </span></li><li class="alt"><span>function showGlobal(){ </span></li><li><span>global $vars; </span></li><li class="alt"><span>print('我使用全局变量:'.$vars); </span></li><li><span>} </span></li><li class="alt"><span class="tag">?></span><span> </span></span></li></ol>
Two very simple files (when the problem was discovered for the first time, it was far more complicated than this. After debugging layer by layer, the minimum environment for reproducing the problem was obtained), func.php is a defined third-party function that uses some global variables. If you put these two files together and execute t1.php, you will find that $vars in showGlobal cannot be displayed. Global is invalid?
2. PHP global variables cannot take effect. The reason for the error
After searching, I found that someone on php.net had proposed it a long time ago, and some people also gave it. Explanation:
It turns out that when include func.php in the run function of t1.php, the scope of the variable $vars in func.php is only within run, while the $vars declared using global in showGlobal is It is required that the one belonging to t1.php is not the run function, so it is empty)
3. PHP global variables cannot take effect and the solution
After knowing the reason, the solution is very simple , you can move include out of run, so that $vars in func.php belongs to t1.php; you can also use global to declare $vars in run, so that $vars that originally belonged to run can be declared as Global (belongs to t1.php);
Although the problem can be easily solved, it is still very uncomfortable to use, because in my phpec framework, the include situation is relatively common, and it is impossible to include the view on demand. Moving to the outer layer and using global, when I use a third-party function, I don’t want to know what global variables it uses. Moreover, when there are more hierarchies,...
Summary of reasons why PHP global variables cannot take effect:
1) Try to reduce include files in multi-level and functions.
2) Try not to use global variables