Home  >  Article  >  Backend Development  >  The role of the PHP keyword global in defining variables_PHP tutorial

The role of the PHP keyword global in defining variables_PHP tutorial

WBOY
WBOYOriginal
2016-07-15 13:32:28736browse

We are using

If the PHP keyword global is used inside a function, it means that the variable used in this function is global, and the global variable is in the entire page It all works. For example

  1. $conf = 1 ;
  2. function conf_test() {
  3. global $conf;
  4. return ++$conf;
  5. }
  6. echo conf_test ()." >< br>"; echo conf_test()."
  7. < br>"; Output:
2

3

If there is no global $conf;, the output will be all 1. The function of the PHP keyword global is to declare that the $conf used in 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, it is easier to understand if the $GLOBALS array is used here. .

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

Output:

<ol class="dp-xml">
<li class="alt"><span><span>$</span><span class="attribute">conf</span><span> = </span><span class="attribute-value">1</span><span>;  </span></span></li>
<li><span>function conf_test() {  </span></li>
<li class="alt"><span>return ++$GLOBALS['conf'];  </span></li>
<li><span>}  </span></li>
<li class="alt">
<span>echo conf_test()."</span><span class="tag"><</span><span class="tag-name">br</span><span class="tag">></span><span>";  </span>
</li>
<li>
<span>echo conf_test()."</span><span class="tag"><</span><span class="tag-name">br</span><span class="tag">></span><span>"; </span>
</li>
</ol>
2

3

PHP Keyword global


http://www.bkjia.com/PHPjc/446123.html

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/446123.htmlTechArticleWe are using the PHP keyword global. If it is used inside a function, it means that the variable used in this function is global. Yes, global variables have an effect on the entire page. For example...
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