faqts : Computers : Programming : Languages : PHP : kms : General

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

26 of 40 people (65%) answered Yes
Recently 6 of 10 people (60%) answered Yes

Entry

How do global variables and functions work?
Do I declare global variables at the top level or inside functions?

Jul 9th, 2003 22:12
Philip Olson, John Coggeshall, Nathan Wallace, Torben Wilson


The only time you ever use the global keyword is inside a function.  
Using it outside of a function has no affect, and will certainly not 
make your variable a "super global".
The idea of scope is documented here:
  http://www.php.net/variables.scope
The basic idea is that functions have their own scope, so variables 
outside of this scope are not available inside the function.  You 
either pass a variable in as a parameter/argument, or, make it 
available with the global keyword.  For example:
<?php
  // A variable defined somewhere in your script
  $myint = 12;
  $myotherint = 42;
  function my_function() {
      // $myint isn't available here, so it's undefined
      echo "My Int is: $myint";
      // now we make it available
      global $myint;
      // and can now use it
      echo "My Int is: $myint";
      // or instead of using global, we can access via $GLOBALS
      echo "My other Int is: {$GLOBALS['myotherint']}";
  }
  my_function();
?>
Result:
My Int is:
My Int is: 12
My other Int is: 42
Also, you can make variables from within the functions available 
outside of the functions, using global, for example:
<?php
  function another_function() {
      global $foo;
      $foo = 42;
  }
  another_function();
  echo $foo;  // 42
??