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
}
$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'
}
// 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'
}
- Printer-friendly version
- Login to post comments
2nd alternative
Anonymous (not verified) — Sat, 12/03/2011 - 09:06You can also use drupal "global" variable version by using the method variable_set and variable_get
// example.module
$myvar = 'foo';
variable_set('myvar', $myvar);
function example_something();
$myvar = variable_get('myvar', 'default value');
No way
Heine — Sun, 20/03/2011 - 11:43No!
Not only does this rely on DB access, it also clears caches, which means a HUGE performance hit (in the order of seconds) and continuous cache stampedes.
Variables have their place, but should not be used to emulate globals.