When using variable_get() in multiple places, how should one avoid duplicating the $default values?

define()? Or is there some built-in Drupal-specific mechanism I'm missing?

2 Answers 2


There is no built in mechanism. In fact, there is a long standing issue to add one http://drupal.org/node/145164.

Defining constants, as you suggested, is the only method I've seen to make it a bit cleaner.

  • Ah! I vaguely recalled seeing that issue once upon a time. Thank you. Also drupal.org/project/variable (mentioned on that issue) looks like a good solution for Drupal 7.
    – smokris
    Feb 21, 2012 at 6:52

A pattern that I often use in custom code, uses OOP. I use this for variable_get, t() and "magic" numbers such as the amount of items in a pager- or limit-query:

class MyModuleHelper() {
  public static $foo = "bar";

  public function v($name) {
    return variable_get("mymodule.{$name}", $$name);

  public function t($identifier, $params) {
    $translated = "";
    $callback = "t_{$identifier}";
    if (function_exist($callback, $this)) {
      $untranslated = $callback();
      return t("mymodule." . $untranslated, $params);
    return $translated;

  private function t_thank_you() {
    return "Thank you, %username";

Then, in the module:

  $helper = new MyModuleNameHelper();

  print "Variable foo:" . $helper->v("foo")
  print "Translate thank_you:" . $helper->t("thank_you")

This has several advantages:

  • Your variables and translations are properly prefixed with mymodule., whithout duplicating that prefix all over the place (DRY!).
  • No need to duplicate your strings and variable values all over the place (DRY+)
  • No need to abuse constants for variable defaults. Constants are constant and should not be abused as value in a variable.
  • Translatable strings are callable with a symbol, t("thank_you") instead of t("Thank you, %username").

And one downside:

  • It is OOP and therefore "un-Drupal-ish".
  • OOP will be "Drupal-ish" as of Drupal 8! :)
    – fureigh
    Apr 2, 2013 at 17:38

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.