Role of the PHP keyword global in defining variables _ PHP Tutorial

Source: Internet
Author: User
The role of the PHP keyword global in defining variables. If we use the PHP keyword global in the function, it means that the variable used in the function is global, and the global variable can work throughout the page. For example, we are using

If the PHP keyword global is used inside the function, it indicates that the variable used in the function is global, and the global variable is available throughout the page. For example

  1. $ Conf = 1;
  2. Function conf_test (){
  3. Global $ conf;
  4. Return ++ $ conf;
  5. }
  6. Echo conf_test ()."< Br>";
  7. Echo conf_test ()."< Br>";

Output:

2

3

If there is no global $ conf;, the output will be 1. The global keyword of PHP is used to declare that $ conf in the function is not local, but global. Or, the $ conf defined in the function is not a variable in the function, but the $ conf defined outside the function (that is, $ conf = 1. in fact, if $ GLOBALS array is used here, it is easier to understand.

We declare a variable $ conf on the page, which is equivalent to defining a $ GLOBALS ['conf'] in the $ GLOBALS array. this $ GLOBALS is globally visible. Therefore, the above code is written in the $ GLOBALS format.

 
 
  1. $conf = 1;
  2. function conf_test() {
  3. return ++$GLOBALS['conf'];
  4. }
  5. echo conf_test()."
    ";
  6. echo conf_test()."
    ";

Output:

2

3

PHP keyword global


If the keyword "global" is used inside the function, it indicates that the variable used in the function is global, and the global variable is available throughout the page. For example...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.