Home  >  Article  >  Backend Development  >  The role of the php keyword global in defining variables

The role of the php keyword global in defining variables

怪我咯
怪我咯Original
2017-06-19 16:01:121105browse

PHPIf the keyword global is used inside a function, it means that the variable used in this function is global, and global variables can work in the entire page. For example,

$conf = 1;  
function conf_test() {  
global $conf;  
return ++$conf;  
}  
echo conf_test()."< br>";  
echo conf_test()."< br>";

output:

2
3

If there is no global $conf;, the output will be all 1. The role of the PHP keyword global is to declare in function that the $conf used within this function is not local, but globally available. In other words, the $conf defined inside the function is not a variable within the function, but the $conf defined outside the function (that is, $conf = 1;). In fact, if $GLOBALSarray## is used here #, it is easier to understand.

When we declare a variable $conf on the page, it is actually equivalent to defining an item $GLOBALS['conf'] in the $GLOBALS array. And this $GLOBALS is globally visible. So the above code is written in $GLOBALS format as

$conf = 1;  
function conf_test() {  
return ++$GLOBALS[&#39;conf&#39;];  
}  
echo conf_test()."<br>";  
echo conf_test()."<br>";

Output:

2
3

The above is the detailed content of The role of the php keyword global in defining variables. 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