Help! - Cannot access a global variable.

Suppose you have the following module. To your dismay, the value of the variable you think is global is not accessible:

// example.module

$myvar = 'foo';

function example_something() {
  global $myvar;
 
  return $myvar; // returns NULL
}

Cause

From http://www.php.net/manual/en/function.include.php

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs.

As module files are loaded by drupal_load, it follows that $myvar is a variable declared in the local scope of the function drupal_load.

Solution

Use the global keyword or $GLOBALS superglobal.

// example.module

// Declare and initialize $myvar as an explicit global:

global $myvar;
$myvar = 'foo';

// Or use the superglobal:

$GLOBALS['myvar'] = 'foo';

function example_something() {
  global $myvar;
 
  return $myvar; // returns 'foo'
}