在WordPress中将类方法作为回调函数传递 [英] Passing Class Method as a Call-Back Function in WordPress

查看:173
本文介绍了在WordPress中将类方法作为回调函数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来传递一个类方法到回调函数参数。

I'm looking for a way to pass a class method to a call-back function parameter.

我通常使用 create_function 如下,但我听说它很慢,使调试困难。

I usually use create_function() as follows but I've heard it is slow and makes it difficult to debug.

add_action('init', create_function('', '$o = new AdminPageClass;'));
class AdminPageClass {

    function __construct() {
        add_action('admin_menu', array(&$this, 'admin_menu'));  
    }
    function admin_menu() {
        add_options_page(
            'Sample Admin Page Class', 
            'Sample Admin Page Class', 
            'manage_options',
            'sample_admin-page_class', 
            array(&$this, 'admin_page'));
    }
    function admin_page() {
        ?>
        <div class="wrap">
            <h1>Hi there</h1>
            <p>Hello World!</p>
        </div>
        <?php
    }
}

它可以做一个额外的功能,像这样;然而,如果可能的话,我想做它没有它。

Of course, it can be done with an extra function like this; however, I'd like to do it without it if possible.

add_action('init', 'load_admin_page_class');
function load_admin_page_class() {
    $o = new AdminPageClass;
}

此外,在它之前实例化类对象使它成为可能,

Also, instantiating the class object prior to it makes it possible but it creates an extra line as well.

$o = new AdminPageClass;
add_action('admin_menu', array(&$o, 'admin_menu'));

class AdminPageClass {

    function admin_menu() {
        add_options_page(
            'Sample Admin Page Class', 
            'Sample Admin Page Class', 
            'manage_options',
            'sample_admin-page_class', 
            array(&$this, 'admin_page'));
    }
    function admin_page() {
        ?>
        <div class="wrap">
            <h1>Hi there</h1>
            <p>Hello World!</p>
        </div>
        <?php
    }
}

类在单独的文件中,所以我更喜欢第一个方法,减少主插件文件中的行。但是如上所述,应该避免使用 create_function()

I always define classes in separate files so I prefer the first method which reduces lines in the main plugin file. But as mentioned, use of create_function() should be avoided.

感谢您的信息。

推荐答案

无需创建一个静态方法。

I found that there was no need to create a static method at all.

add_action('admin_menu', array(new AdminPageClass, "admin_menu"));

class AdminPageClass {

    function admin_menu() {
        add_options_page(
            'Sample Admin Page Class', 
            'Sample Admin Page Class', 
            'manage_options',
            'sample_admin_page_class', 
            array(&$this, 'admin_page'));
    }
    function admin_page() {
    ?>
        <div class="wrap">
            <h1>Hi there</h1>
            <p>Hello World!</p>
        </div>
    <?php
    }       
}

这篇关于在WordPress中将类方法作为回调函数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆