Setting global variables in settings.php - Drupal 7

To set a global variable which will be persistent across a site, you can use a conf array in the sites settings.php file. These values are cached by the site, and can be retrieved using variable_get. It's also possible to use other functions in relation to these variables, like variable_set (to set a variable), and variable_del (to delete a variable). I'm not going to delve into those now, but check out the links at the end of the post for more info.

If you want to find out what global, persistent variables are currently available as well as their values you can use the Variable module to do it via a UI interface. If you are using Drush you can download a text file listing all the variables and their values using drush vget > variables.txt.

Defining the global variables in settings.php

You will notice that there is actually a 'Variable overrides' section in your settings.php file, but you aren't actually required to put the code there. Below are two examples of setting the conf - one being a single value an the other an array. To avoid problems make sure that your persistent variable names always use lower case.

$conf['my_value'] = 'Here is my global value';

$conf = array(
'my_value_1' => 'A global variable value',
'my_value_2' => 'Here is another one',
'my_value_3' => 'And yet another variable value here',
);

Getting persistent variables 

To retrieve these values use the variable_get function as shown in the below examples. These can be used in something like a custom module or template file.

Notice the default value which can be set, it will be used if nothing has been set for the global value, but can also be left blank if not required.

variable_get('my_value', 'Default value here if needed');

$variable1 = variable_get('my_value_1', '');

 

Justin Chevallier

Justin Chevallier

Avid Drupal site builder & user for +10 years.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.