Question

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
Was it helpful?

Solution

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.

OTHER TIPS

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top