0

I am trying to use OOP in wordpress. Sample code below. As you can see I have to put global $wpdb in each method. I want to avoid duplicating this line in each method.

Is there a way to set this in constructor or into some protected/private variable so i don't have to put that in every function?

    class HouseRepository {
        public function functionB() {
            global $wpdb;

            $results = $wpdb->get_results();

            return $results;
        }

        public function functionA() {
            global $wpdb;

            $results = $wpdb->get_results();

            return $results;
        }
    }

I tried doing in constructor (and removed from each method) it doesn't work.

function __construct() {
    global $wpdb;
}

1 Answer 1

3

You can try setting a reference to the global $wpdb variable to a class property or static property.

function __construct() {
    global $wpdb;

    $this->wpdb = $wpdb;
    // or
    self::$wpdb = $wpdb;
}

And later access that property inside the methods.

public function functionA() {


    $results = $this->wpdb->get_results();
    // or
    $results = self::$wpdb->get_results();

    return $results;
}

Thanks.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh thats what i wanted. Thanks :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.