According to the general program of thinking, the variables outside the function should be considered as global variables, if it is a global variable, then call in the function is completely no problem. This article is mainly to share with you the PHP call function outside the variable method, I hope to help everyone.
It seems that PHP and our traditional thinking a bit of a problem, then the global variables in PHP, I deliberately write code to try.
1. Define the direct output externally with global:
Global $mytext; $mytext = "Nihao"; function Chao_echo () {echo $mytext;} Chao_echo ();
Result: no output.
2. Output with Globals array:
Global $mytext; $mytext = "Nihao"; function Chao_echo () {echo $GLOBALS [' mytext '];} Chao_echo ();
Result: the output is normal.
3. Declare variables outside the function globally within the function:
$mytext = "Nihao", function Chao_echo () {global $mytext; echo $mytext; Echo $GLOBALS [' mytext '];}
Chao_echo ();
Result: direct output or with Globals global array output is OK.
4. Pass the function external variables in parameters:
$mytext = "Nihao"; function Chao_echo ($mytext) {echo $mytext;} Chao_echo ($mytext);
Result: can be output.
To summarize, in PHP, there are three ways to refer to variables outside the function in a function:
1. Outside the function global declaration, the function uses the $globals array reference.
2. function within the global declaration, function within the $globals array or direct reference.
3. A parameter is passed when the function is called.