Home  >  Article  >  Backend Development  >  PHP calls variable method outside function

PHP calls variable method outside function

小云云
小云云Original
2018-03-21 14:22:178014browse

According to the general programming ideas, variables outside the function should be regarded as global variables. If they are global variables, then there is no problem in calling them in the function. This article mainly shares with you the variable methods outside of PHP calling functions, hoping to help you.

It seems that PHP has some problems with our traditional thinking. So what are the global variables in PHP? I specially wrote the code to try it out.

1. Use global definition to output directly externally:

global $mytext;
$mytext=”nihao”;
function chao_echo(){
echo $mytext;
}
chao_echo();

Result: No output.

2. Use GLOBALS array output:

global $mytext;
$mytext=”nihao”;
function chao_echo(){
echo $GLOBALS['mytext'];
}
chao_echo();

Result: The output is normal.

3. Globally declare variables outside the function within the function:

$mytext=”nihao”;
function chao_echo(){
global $mytext;
echo $mytext;
echo $GLOBALS['mytext'];
}

chao_echo();
Result: Either output directly or use GLOBALS global array output. .


4. Pass the external variables of the function into the 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 reference variables outside the function within a function:

1. Global declaration outside the function, and use the $GLOBALS array reference within the function.

2. Global declaration within the function, $GLOBALS array within the function or direct reference.

3. Pass a parameter when calling the function.

Related recommendations:

php examples share how to dynamically call functions

What is php calling functions, parameter transfer, variable functions, references

How to call functions within PHP strings_PHP tutorial

The above is the detailed content of PHP calls variable method outside function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn