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();
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?
}
}
在更深的搜索中,我的意思是更深的搜索;我发现a.)即使它有效,在全局变量中使用变量也是不好的。b.)用函数检索应该是可以的。