Heine

  • home
  • drupal
  • about
Home

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

Average: 5 (1 vote)
‹ 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
  • Login to post comments

2nd alternative

Anonymous (not verified) — Sat, 12/03/2011 - 09:06

You 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');

  • Login to post comments

No way

Heine — Sun, 20/03/2011 - 11:43

No!

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.

  • Login to post comments

Recent posts

  • In doubt? Read the specs!
  • About the Webform SA
  • Psalmen voor Altblokfluit
  • Unserializing user-supplied data, a bad idea
  • Planet Drupal past and current
more

Security reviews

  • Afraid custom code makes your site vulnerable?
  • You don't really trust that module you just downloaded from Drupal.org?

Sleep better after a security review.

Tags

bladmuziek blood donation blood supply CSRF Drupal Input Format modx MSM Performance Planet Drupal Security Varnish
more tags
  • home
  • drupal
  • about

Copyright © 2011 by Heine Deelstra. All rights reserved.