[resolved] Should I declare $wpdb as global in my plugin? (3 posts)

  1. maerk
    Posted 10 years ago #

    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.

  2. Kafkaesqui

    Posted 10 years ago #

    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:


  3. maerk
    Posted 10 years ago #

    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.

Topic Closed

This topic has been closed to new replies.

About this Topic