Support » Plugins and Hacks » Should I declare $wpdb as global in my plugin?

  • Resolved maerk

    (@maerk)


    I’m writing a plugin that needs to query the database, and I’m using the $wpdb class of functions to do it.

    I’m finding that if I don’t declare global $wpdb at the beginning of the function, I get an error:

    Call to a member function query() on a non-object in ...

    It works perfectly with the global declaration, but I was wondering whether declaring $wpdb global was the best idea. The codex documentation seems just to assume that it should work straight off, which is why I’m concerned.

Viewing 2 replies - 1 through 2 (of 2 total)
  • It all depends on how a function in ones plugin is called, but it’s usually necessary to scope $wpdb to global. That the Codex doc doesn’t mention this is a bit of an oversight (that’s easily rectified).

    The general topic of class scoping in a plugin is mentioned here, which I’ll have the Codex page refer to:

    http://codex.wordpress.org/Writing_a_Plugin#User_Interfaces

    Thank you!

    I’ve heard in places that scoping things to global isn’t always the best idea, but I think that has to do with variables where GET or POST data is concerned.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Should I declare $wpdb as global in my plugin?’ is closed to new replies.