Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Let's say I set a variable in settings.php: $conf['var'] = foo;

In my module or theme code, I can access this with either: variable_get('var'); or $GLOBALS['conf']['var'];

Which is the preferred method and why?

share|improve this question
1  
I think this might be opinion base and/or base on the use case. IMO, I will use variable_get('var'); – darol100 Jan 21 at 19:07
up vote 6 down vote accepted

Pros:

  • variable_get() provides the ability to give you a fallback if it doesn't exist
  • using the variable directly could wind up with a PHP notice if it doesn't exist is able to use the variable system (and any available hooks)
    • accesses all the variables (settings.php, variables in the DB, etc.) - a one stop shop. I don't believe $conf does this. A simple print_r($GLOBALS['conf']) would show if that is true or not

Cons:

  • accessing the variable directly is more efficient since it doesn't execute any functions or require any logic

Personally I would use variable_get() because of the fallback functionality and ability to tap into whatever other sources the variable system may provide

share|improve this answer
2  
variable_get() is just a thin wrapper around $conf, and doesn't touch the DB or settings.php directly. Part of bootstrap is to load all variables from cache/database and merge them with any $conf from settings.php. Start reading from _drupal_bootstrap_variables() and then variable_initialize() to see how this works. – MPD Jan 21 at 23:03
2  
Wow. You are correct. I guess I valued the fallback so much I assumed it did more. Every time I worked with $conf it was way too early in the process before it merged variables. – mike Jan 22 at 5:19

It is preferable to use variable_get() instead of $GLOBALS['conf']['var'].

Despite being gone in Drupal 8, you always want to program to the API instead of programming to the implementation.

It is highly unlikely, but there could be some change that pops up in Drupal 7 where there is a difference between the two. For example, a future version could include a hook_variable_alter() to allow modules to muck with variables between the database and their usage.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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