Heine

  • Home
  • Drupal
  • About
Home » Guides » Drupal Developer FAQ

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'
}

‹ FAPI - How to decrease/increase the text limit of textfields? up How do I add a class to a link generated with l() ›
  • Printer-friendly version

Recent posts

  • Teampassword manager's password generator is biased
  • Other vectors for SA-CORE-2014-005?
  • Lazy loading: hook_hook_info is for hook owners only.
  • "Always offline" problem in EA's Origin due to antivirus
  • From bug to exploit - Bakery SSO
more

Security reviews

I provide security reviews of custom code, contributed modules, themes and entire sites via LimoenGroen.

Contact us for a quote.

Follow @ustima

Copyright © 2021 by Heine Deelstra. All rights reserved.

  • Home
  • Drupal
  • About