Using variable in two functions

As a matter of good coding practice, global variables are problematic at best, dangerous at worst. They should be avoided if at all possible. Why? Because what if some other plugin developer also decides to define$a as a global? Whatever that plugin is doing will now overwrite your global $a and yours has the potential to wreak havoc with theirs.

WordPress sets a bad precedent by using so many of them within its own code, but the good news is that you don’t have to, and in most cases you can avoid adding to the mess of them that are already there.

One easy way to avoid a global is to wrap the variable in another function that will return a value:

function my_theme_array() {
    return array('asdf', 'asdf', 'asdfasd');
}

This would allow you to retrieve it from within other functions while keeping it in local scope and out of conflict with other code:

function themeslug_query_vars( $qvars ) {
  $a = my_theme_array();        
  ... // Now use $a for whatever.
}

function search_pre_get_posts($query){
  $a = my_theme_array();
}

If you want to be able to change the contents that the function returns rather than having your array hard-coded into the my_theme_array() function, you could set up the function to take parameters that would change the currently set values of the array:

function my_theme_array_ver_2( array $new_values = null ) {
    static $my_array = array('asdf', 'asdf', 'asdfasd'); // default values
    if ( isset( $new_values ) ) {
        $my_array = $new_values;
    } else {
        return $my_array;
 }

So now you can call the function to set it’s return value:

my_theme_array_ver_2( array( 1, 2, 3 ) );

or you can simply ask it to return whatever value is currently set:

$a_this_time_around = my_theme_array_ver_2();

Leave a Comment