7

I am new in OOP PHP and I am trying to use $wpdb (WORDPRESS) object in some of my custom classes but have no idea how to do it. Every time I try to implement basic operations with $wpdb results in fail. I need some basic stuff like get_results(),.... So how to do something like this:

global $wpdb;

$my_custom_table = $wpdb->prefix . "table_name";

$table_content = $wpdb->get_results("SELECT * FROM ".$my_custom_table);

and put it into my class like this:

Class MyClass{

     public function table_results(){
            //put in here
            return $this->table_content;
     }
}

I need that class in separate file so I could easily call to it.

adeneo
  • 312,895
  • 29
  • 395
  • 388
Bambino Negro
  • 115
  • 1
  • 8
  • You'd still have to just put the first code into the function in the second code. – adeneo Jun 28 '15 at 06:08
  • http://stackoverflow.com/a/5418972/4563843 < use this as starting point, there are atleast 2 top answers to help you get going - and also, read about basics of PHP classes. – Siim Kallari Jun 28 '15 at 06:15
  • It's not working. I forgot to mention that these are files for my plugin. – Bambino Negro Jun 28 '15 at 06:15
  • learn to write a simple wordpress plugin then? https://codex.wordpress.org/Writing_a_Plugin – Siim Kallari Jun 28 '15 at 06:22
  • First 3 lines of code works perfectly fine in separate file, but I need it in my class - and when I put it in - nothing works. I have no idea how to fix this. – Bambino Negro Jun 28 '15 at 06:45
  • Yes it is because you do not understand how classes in php, what is encapsulation and what is dependency injection, google these things, start with learning "The basics of PHP Classes" – Siim Kallari Jun 28 '15 at 07:14

1 Answers1

21

Try this...

<?php
class MyClass {

private $wpdb;

public function __construct()
{
    global $wpdb;
    $this->wpdb = $wpdb;
}

public function table_results(){
    $my_custom_table = $this->wpdb->prefix . "table_name";

    $table_content = $this->wpdb->get_results("SELECT * FROM $my_custom_table");
    return $table_content;
}
}
Oversun
  • 356
  • 2
  • 6
  • Thanks. I came up to something very similar to this. I was missing __construct all the time.:( Oh my OOP is so bad :( – Bambino Negro Jun 28 '15 at 08:31
  • 1
    When I use this in my plugin class I get a "Uncaught Error: Using $this when not in object context". – TARKUS Jan 31 '20 at 22:43