Understanding PHP Globals and Variable Scope in WordPress

One of the most maligned features of WordPress is the use of “PHP global variables.” Whether you love them or hate them, global variables probably aren’t leaving WordPress soon. So today we’ll cover all there is to know about them. How to think about them. How you, in PHP, make variables global, access WordPress’s global variables, and a little about the theory and debate about global state in software applications.

Should You Use Global Variables in PHP?

There are huge decades-long discussions in software development circles about why heavy reliance on globally scoped variables is a bad design decision. That debate is beyond the scope of what I want to cover here. (If that topic is interesting to you, the C2 Wiki article on it is a good starting point for understanding the arguments.) Suffice it to say that they’re bad because they can cause “spooky action at a distance.” Or, in other words, because global variables are “global,” someone else’s change to a global variable can break your code. And they were only able to do that because it’s a “global.”

The primary point in favor of global variables? They’re a relatively easy and robust way to share information in all the parts of a web application. As we’ll see, just drop the global keyword into your PHP and you’re off to the races. More important than this discussion is a simple understanding of the meaning and implications of PHP global variables for WordPress development, so let’s get started.

Brief Interlude on our way to understanding PHP Global Variables…

One quick thing before we get to how you’ll go about using global variables in PHP. If you’re looking to learn WordPress development, we’ve written the best guide to it out there:

The Best Way to Learn WordPress Development

Get Up and Running Today!

Up and Running is our complete “learn WordPress development” course. Now in its updated and expanded Third Edition, it’s helped hundreds of happy buyers learn WordPress development the fast, smart, and thorough way.

Here’s what they have to say:

“Other courses I’ve tried nearly always lack clear explanations for why WordPress does things a certain way, or how things work together. Up and Running does all of this, and everything is explained clearly and in easy-to-understand language.” -Caroline, WordPress freelancer

“I think anyone interested in learning WordPress development NEEDS this course. Watching the videos was like a bunch of lights being turned on.” -Jason, WordPress developer

You Keep Using that Word… What is “Variable Scope” in PHP?

What this means is that any given unit of PHP will either have access to variables in the global scope, or only have access to the variables declared inside the currently executing function.

Scope is a popular brand of mouthwash in the United States. But it’s also, and more importantly, about what’s relevant and visible to who and where. People use the phrase “out of scope” when talking about activities or ideas that aren’t currently relevant to what they’re working on, and that’s got a lot to do with variable scope.

Programming languages like PHP are written such that variables are accessible only within in a certain context, or scope. This is done it various ways, and based on various rules in different languages. But the purpose of variable scopes is to prevent the problem that one part of a program may set $i to 5, and while it’s waiting to use that value, and another part sets it to 981235792 or “cucumber.” If they’re both using the same $i, one of those parts of the program is highly likely to malfunction.

Variables are given scope to prevent programs (and programmers’ heads) from exploding. The specific rules that control what variables are accessible in which places vary from programming language to programming language. What’s relevant to someone interested in WordPress and PHP is the specific way it works in that context.

PHP as a language uses function scoping. What this means is that any given unit of PHP will either have access to variables in the global scope, or only have access to the variables declared inside the currently executing function. And variables declared in a function are not going to be available globally unless they explicitly declare that they are. I could keep speaking abstractly, but I think it’s best if we get concrete with the PHP: we’ll declare global variable inside functions, and access global scope as well.

PHP Global Variable Example: Playing with Scope in PHP

In this section I just want to run you through what all this global variable scope stuff looks like in some basic PHP. Declaring a global variable, accessing a global variable, and more can be explains with this non-WordPress sample PHP code:

$global = "I am a global variable because I wasn't defined inside a function.";

my_global_function();
my_nonglobal_function($global);
function my_global_function() { 
     global $global; 
     echo $global;
}

function my_nonglobal_function($global) {
     echo $global;
}

function make_something_else_global() {
    global $second_global;
    $second_global = "I'm global becuase the word global was used inside a function.";
}
make_something_else_global();
echo $second_global;

As we said in the last section, there are really only two relevant scopes in PHP for variables you create: global and function. (There is a third type of scope, but if you want to know more about superglobals like $_GET, $_POST, and $_REQUEST, but they’re too big of a topic to tackle here.)

Declaring: In PHP, Make a Variable Global

If you desire in PHP to declare global variable, you can just do it outside of a function. That’s because any PHP variable that is not inside of a function (and thus isn’t function-scoped) is global. The value of the variable $global will simply work anyway after the line of code that declare it. And because we’re declaring $global outside of a function, it will automatically have global state.

But in a lot PHP for WordPress, you’ll be inside of a function. This is often because you’re working with a WordPress hook. To make a variable available everywhere (globally) from inside a function means that you must first declare that variable as global. Then you can assign that variable to anything you like. That’s what we’re doing inside of the make_something_else_global function in the code section above.

That’s how to set global variable in PHP: first make sure you’ll have a variable be global, either by position (outside of any function) or by using the global keyword. Then you just set it, or set it again. Even 100 times. PHP doesn’t care.

PHP Access Global Variable, “import” with global keyword

Inside of a PHP function, a global variables (declared elsewhere) can be accessed in two ways. First (and most common), is accessing it using the global keyword. This is what our first called function, my_global_function, does. By asserting that it wants the global variable $global, the echo — which is just PHP vocabulary for “throw onto the screen” — can output the string that we declared in the first line of the example. If we’d skipped the global line, we’d — depending on settings — either see a PHP error, or nothing on the screen at all. Neither is what we wanted.

This code shows another way that we can use the predeclared variable $global in the my_nonglobal_function. To do that, we can pass $global it into the function as a parameter. This allows us to be a little more certain about what variable we’re truly getting in the function, because it’s a hand-off. and it allows us to to skip straight to the echo $global without a stop off to “import” the variable. This is a way to avoid using to many PHP globals.

As you can see, these two functions that both accomplish the same thing. You’ll see both methods occur in various places in various PHP projects. Use of global has fallen out of favor in the PHP community because of the risk that before our function got around to access $global it could easily have been changed to anything and we’d be left having made a wrong assumption about it and quite possibly causing errors. The method of passing the relevant variables into the function when it is called is preferred in projects that don’t worry about backwards-compatibility as much as WordPress.

A PHP Global Array: Just like a Variable

One last note: you can assign almost anything to a (global) variable in PHP. Whether a string, object, or array, all you need to do to make a global array in PHP is to follow the step we outline above. Primarily: declare global $array that’s really all there is to make a PHP global array.

And while you might think, “I’m doing global better” because you only have “one” global array, I will caution you that from a precaution principle perspective, anything that varies independently should be consider a free global variable. Each element of that array is a global variable. Even if you’ve shoved them all in an array labelled, say, $global_array_of_variables.

WordPress Global Post ($post): Variable Scope in WordPress

As I said at the top, WordPress relies heavily on PHP global variables. (Here’s the list of all its globals.) As such, it is exceptionally common that you’ll see a function start with a line like:

global $post;

Hopefully by now you’ve got a pretty good idea of what this is doing: importing in the entire global $post variable — which template tag functions like the_title() (or ones you make yourself) rely on — to local scope so it can act on it. This is so common you’ll see people forgot the need to declare the global or add the line at the top of their function when it’s not really necessarily. (It’s usually unnecessary because the programmer never accesses anything on $post directly after they “import” it from the global scope.)

Another prime example, other than inside the loop with template tags like the_ID() and the_content() of where global scope is used within WordPress is the mythical Loop itself. If you’ve written a custom WP_Query you may have suspected it, but the way you can use object-less methods like have_posts() and the the_post() inside of your template hierarchy files is that under the hood you’re calling those same methods on a global instance of WP_Query that WordPress has set up for you. (I like to tell beginners to just think of this as a “magic bag of posts,” but under the hood experts understand that it’s just a WP_Query object.)

What We’ve Learned about PHP Global Variables

Where you can avoid it, it’s generally considered a better idea to not add things to the PHP global scope. Given a choice between passing in a variable to the new function using it as a parameter, or adding your variable to the global scope, its best practice to do the former. But because WordPress is so conservative, global variables aren’t likely to leave us anytime soon. For that reason, you’ve earned a valuable power by understanding them. Happy hacking!


1 Response

Comments

Add a Comment

Your email address will not be published. Required fields are marked *