如何在可湿性粉剂插件中从这个类的外部访问函数?

时间:2013-05-22 作者:Derfder

我正在开发一个名为WP的插件。DD_Awesome_Plugin 这是我迄今为止的代码(简化版,类函数中没有额外的代码逻辑):

class DD_Awesome_PLugin {

    public function __construct()
    {

    }

    public function add_menu_page()
    {
        add_options_page(\'DD Awesome PLugin\', \'DD Awesome PLugin\', \'administrator\', __FILE__, array(\'DD_Awesome_PLugin\', \'display_options_page\'));
    }

    public function display_options_page()
    {
        $plugin_options = get_option(\'dd_my_awesome_plugin\');
        echo "Here we go admin!";

        /* and after echo I need to triger a function "trigger_me_from_class()" that is located outside of the class. */
    }

}


add_action(\'admin_menu\', function() {
    DD_Awesome_PLugin::add_menu_page();
});

add_action(\'admin_init\', function() {
    new DD_Awesome_PLugin();
    include_once dirname(__FILE__) . (\'/simple_html_dom.php\');
});


 /* just trigger this function "trigger_me_from_class" from "display_options_page" function (situated in DD_Awesome_plugin class above) */
public function trigger_me_from_class()
{
    $str = date(\'Y-m-d H:i:s\', time());
    wp_mail(\'[email protected]\', \'DD success message\', "Success at $str." );
}

1 个回复
最合适的回答,由SO网友:fuxia 整理而成

为类实例创建静态getter:

class DD_Awesome_Plugin
{
    /**
     * Plugin main instance.
     *
     * @type object
     */
    protected static $instance = NULL;

    /**
     * Access plugin instance. You can create further instances by calling
     * the constructor directly.
     *
     * @wp-hook wp_loaded
     * @return  object T5_Spam_Block
     */
    public static function get_instance()
    {
        if ( NULL === self::$instance )
            self::$instance = new self;

        return self::$instance;
    }

    public function add_menu_page()
    {
        add_options_page(
            \'DD Awesome PLugin\', 
            \'DD Awesome PLugin\', 
            \'administrator\', 
            __FILE__, 
            array( $this, \'display_options_page\' )
        );
    }
}
现在,您可以通过以下方式获得插件实例:

add_action(\'admin_menu\', function() {
    DD_Awesome_Plugin::get_instance()->add_menu_page();
});
或:

add_action( 
    \'admin_menu\', 
    array( DD_Awesome_Plugin::get_instance(), \'add_menu_page\' ) 
);

结束