-1

TL;DR: Say I have a global instantiated class

$GLOBALS['my_plugin'] = instance(); 

and I want to use it somewhere else, but I dont know the name 'my_plugin'. Actually I do of course, but my helper files don't. In order to So I use;

$plugin_name = 'my_plugin';
global $plugin_name, ${$plugin_name};

And it works I can access $my_plugin variable and use the object just fine. What I am doing is basically making use of "variable variables",but it somehow feels weird. Is it OK ? Or is there a better way to tackle this.

Long Version

// contents of plugin.php
class myplugin_class {
    $_instance = null;
    public $plugin_name = 'my_plugin';

    public function __construct() {
        $this->init();
    }
    public static function instance() {
        if ( is_null( self::$_instance ) ) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
    function init() {
       $this->assign_global();
       $this->include_helper();
    }
    function assign_global() {
        global $plugin_slug;
        $plugin_slug = $this->plugin_name;
    }
    function include_helper() {
        include_once('helper.php' );
    }


}//end class
function plug_inst() {
    return myplugin_class::instance();
}

$GLOBALS['my_plugin'] = plug_inst();

Helper.php

// contents of helper.php
class helper_class {
    public function __construct() {
        $this->some_function_that_needs_my_plugin_object();
    }
    function some_function_that_needs_my_plugin_object() {
        global $plugin_slug, ${$plugin_slug};
        print_r(${$plugin_slug});
        //It gives me the $my_plugin object I want. It's all good, it works. But is it OK?
    }
}
Emin Özlem
  • 809
  • 7
  • 13

1 Answers1

1

Upon deeper, I mean deeper search; I found out that a.) Even if it works it is not OK to use variable variables in globals. b.) It should be OK to retrive it with a function.

Emin Özlem
  • 809
  • 7
  • 13