Skip to content

PHP – use Global Variables in Class

If you have a need to use a global variable in a PHP class this could be useful. In my case, I want to use globalise a database table name in WordPress which generates its prefix using the $wpdb object.

global $wpdb;
$WP_GLOBALS = array(
    'table_name' => $wpdb->prefix . 'organisations'
class Organisations {
    // Instantiate new variable in class
    protected $glob;
    public function __construct() {
        // Self explanatory
        global $WP_GLOBALS;
        $this->glob =& $WP_GLOBALS;
    public function tableName() {
        return $this->glob['table_name'];
// Access outside of class
$o = new Organisations();
echo $o->tableName(); // wp_organisation
// Set new value for $WP_GLOBALS['table_name'];
$WP_GLOBALS['table_name'] = $wpdb->prefix . 'posts';
echo $o->tableName(); // wp_posts


10 years + experience in web development working with lots of different technology.

Published inPHPWordPress

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *