Use Functions, Not Globals

WordPress is often maligned because of it’s profuse use of global variables.

It’s a legitimate complaint. Globals leave a lot of room for messing things up.

If you’re doing much work with WordPress development, themes and plug-ins, it’s tempting to throw more global variables into the mix.

Don’t. Just don’t.

Specifically, don’t do this:

$EssentialThemeVariable = 'Secret Ingredient';

function do_something_awesome() {
  global $EssentialThemeVariable;

 // do something with $EssentialThemeVariable
}

Depending on where you define $EssentialThemeVariable, you might or might not be able to access it this way. More than likely not.

Instead, define your variable (and make changes to your variable) inside a function that returns the value you need, like this:

function get_essential_variable( $something ) {
  $EssentialThemeVariable = 'Secret Ingredient';
  if ( $something == 10 ) {
    $EssentialThemeVariable = 'Love';
  } elseif ( $something == 12 ) {
    $EssentialThemeVariable = 'Salt';
  }
  return $EssentialThemeVariable;
}

Then, any time you need it, you can get it back in function scope by calling the function that returns it, like such:

function do_something_awesome() { 
  $EssentialThemeVariable = get_essential_variable( 10 ); 
                          // Passing 10 sets Variable to 'Love'
  // do something with $EssentialThemeVariable
}

Now you know why its called functions.php, not global.php.

Happy coding.