[ACCEPTED]-Wordpress wpdb undefined variable-wordpress
I needed to use global $wpdb;
in my function.
0
One note to add: You cannot use global
inside 13 a class, and of course you have to use global
in 12 order to get your objects to work using 11 $wpdb
.
While you can't use global
immediately inside a class, you 10 must declare $wpdb
as global
inside a function inside the class, and 9 this does work.
e.g. This gives you an error:
class wpdb_test {
global $wpdb; // can't use global as a direct 'child' of a class
public function __construct () {
...
}
}
Because 8 global
can't be used directly inside a class. Likewise, simply 7 referencing $wpdb
inside the class also gives you 6 an error because the object doesn't know 5 what $wpdb
is. You have to declare $wpdb
as global
from 4 inside a function that is inside your class.
e.g. This 3 works just fine:
class wpdb_test {
public $variable_name;
public function __construct () {
global $wpdb; // safe to use because it's inside a function
...
}
}
...and because $wpdb
has been 2 declared global
inside a function inside a class you 1 are able to use it.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.