Passing Class Method as a Call-Back Function in WordPress

后端 未结 2 1716
孤独总比滥情好
孤独总比滥情好 2021-02-06 15:33

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

I usually use create_function() as follows but I\'ve heard it is slow and m

相关标签:
2条回答
  • 2021-02-06 15:59

    Create a static method which returns the array containing the class instance and the method name.

    /* 
        Plugin Name: static method callback demo
    */
    
    add_action('admin_menu', AdminPageClass::_admin_menu());
    
    class AdminPageClass {
    
        static function _admin_menu() {
            $class_name = get_class();
            $classinstance = new $class_name();
            return array(&$classinstance, "admin_menu");
        }
        function admin_menu($instantiate=false) {
            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
        }
    }
    
    0 讨论(0)
  • 2021-02-06 16:00

    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
        }       
    }
    
    0 讨论(0)
提交回复
热议问题