全局变量中的变量:“全局变量{变量}”。它有效,但可以吗?

Variable in global variable: "global variable{variable}". It works, but is it OK?

提问人:Emin Özlem 提问时间:3/29/2015 更新时间:3/29/2015 访问量:29

问:

TL的;DR:假设我有一个全局实例化类

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

我想在其他地方使用它,但我不知道“my_plugin”这个名字。实际上我当然有,但我的帮助程序文件没有。为了 所以我使用;

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

它可以工作,我可以访问 $my_plugin 变量并很好地使用该对象。我正在做的基本上是利用“变量”,但不知何故感觉很奇怪。可以吗?或者有没有更好的方法来解决这个问题。

长版

// 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();

帮助程序:.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?
    }
}
php oop wordpress 全局 变量变量

评论


答:

1赞 Emin Özlem 3/29/2015 #1

更深入,我的意思是更深入的搜索;我发现 a.)即使它有效,也不能在全局变量中使用变量。b.)使用函数检索它应该是可以的。