How PHP Globals Work


I had a reminder of how globals work recently. I was trying to perform a WordPress query using the $wpdb global for the database. The global was declared at the top of the file like this:

global $wpdb;

Simple enough. Then I thought I would just use it inside of another function, since it’s global. Functions, however, don’t recognize the global when it is used, unless you tell the function that it is supposed to use the global, rather than a new function. So you will need to declare it again within the function.

global $wpdb;

Then you can use it within the function just like any other variable.

What Are Your Thoughts?

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