Log in / create account | Login with OpenID
DocForge
Programmer's Wiki

PHP/global

From DocForge

< PHP

global is a PHP construct which makes a global variable available in local scope. A variable is initialized globally when it's first used outside of any function or class. Global variables can also be accessed with the superglobal array $GLOBALS.

PHP superglobal variables are always available in every scope. They do not require use of the global keyword.

[edit] Example

$string = 'abc';
 
function foo() {
  $string = 'def';
  /* Local variable $string now has the value 'def' 
     while global variable $string retains the value 'abc'.  */
}
 
function bar() {
  global $string;
 
  $string = 'def';     // Global variable $string now has the value 'def'
}
 
foo();
echo $string;  // Outputs 'abc'
bar();
echo $string;  // Outputs 'def';

[edit] See Also

Do you have information or insights to contribute to this article? Please feel free to edit this page. Ask questions or contribute to the discussion on this article's talk page.