简体   繁体   中英

global variables scope in php

I didn't understand this sentence from php.net: Note: Using global keyword outside a function is not an error. It can be used if the file is included from inside a function.

what does it mean? can anyone demonstrate briefly?

Global Variables:

In contrast to local variables, a global variable can be accessed in any part of the program. However, in order to be modified, a global variable must be explicitly declared to be global in the function in which it is to be modified. This is accomplished, conveniently enough, by placing the keyword GLOBAL in front of the variable that should be recognized as global. Placing this keyword in front of an already existing variable tells PHP to use the variable having that name.

Example

$somevar = 15;

function addit(){
   GLOBAL $somevar;
   $somevar++;
   print "Somevar is $somevar";
}

addit();

Output

Somevar is 16

"It can be used if the file is included from inside a function" means that it will even work like this:

page.php

<?php
  global $d;
  $d = "HI";
?>

index.php

<?php
  getpage();

  function getpage(){
     include 'page.php';
     echo $d;
  }
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM