How PHP Globals Work

November 14, 2012

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.

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive