4

I need to define a global variable. Where should I define it?

  1. I will not use the global variable in template files
  2. I should not use settings.php
  3. I will only use the global variable in all the custom module files

2 Answers 2

8

Personally, I would either write module that abstracts away the need for a global variable, or at least has a getter function for retrieving it. Something like

function foo_get_the_service ()
{
  static $service;

  if (! isset($service)) {
    $service = foo_init_the_service();
  }

  return $service;
}

Several Drupal API functions do something similar (eg, menu_get_active_trail() and menu_set_active_trail());

And then preferably, your module would also have helper functions so you don't need to access the global directly. If something really does need the global, then you would use the getter.

If your global is an instance of a proper PHP class, then you could look into using a real singleton.

0
3

I think what you're looking for is making use of Drupal's variables using variable_set() to create it and variable_get() to retrieve it for use in your modules.

To use variable_set() just provide the variable name and value: variable_set(name, value).

To use variable_get() you just need to provide the variable name and default value (to be used if not yet set): variable_get(name, default_value).

2
  • 3
    Just keep in mind that this is really meant for config type variables and not really meant for passing around stuff at runtime on normal pages. The reason is that variable_set() clears all caches, so this comes with a pretty significant performance hit.
    – mpdonadio
    Commented Nov 9, 2011 at 15:20
  • The variable_set() and variable_get() functions are made to set/get a persistent variable. The value will be stored in the database and shared by all requests (and all users). The question is not clear if this is a wanted feature. Commented Nov 29, 2011 at 20:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.