2013-03-01 63 views
0

这是代码的一部分,参与我的问题外:调用一个函数的类

class My_Box { 
    function __construct($args) { 
    add_action('admin_footer', array(__CLASS__, 'add_templates')); 
    } 
    static function add_templates() { 
    self::add_template('list'); 
    self::add_template('grid'); 
    } 
    private static function add_template($name) { 
    echo html('script',array(/*args*/)); 
    } 
} 

在上面的代码中ADD_ACTION需要的参数是字符串这样的:

add_action('handle','function_name'); 

现在我需要在类之外运行add_action语句,我想这样的事情:

add_action('wp_footer', My_Box::add_templates()); 

这个状态发出“注意:未定义偏移量:0”的调试消息。

如何正确编写此add_action语句?

+2

'ADD_ACTION( 'wp_footer',阵列( “My_Box”, “add_templates”));'? – Passerby 2013-03-01 07:18:17

+0

这不适用于课外。 – 2013-03-01 07:19:10

回答

0

要传递作为第二个参数,以add_action阵列类的取出是一个回调。数组中的第一个值是类名,第二个是该类上的静态方法的名称。在一个类__CLASS__内将包含该类的名称。因此,要在其他地方进行相同的调用,只需用实际的类名替换即可。

add_action('wp_footer', array('My_Box', 'add_templates'); 

欲了解更多信息的回调是如何定义的,请参阅:http://www.php.net/manual/en/language.types.callable.php

1

在类

add_action('handle', array(get_class(), 'function_name')); 

add_action('handle', array('class_name', 'func_name')); 
+0

'get_class()'和'__CLASS__'在这里是等价的 – FoolishSeth 2013-03-01 07:28:46

0

结帐这个http://codex.wordpress.org/Function_Reference/add_action#Using_add_action_with_a_class

要使用时,你的插件或主题建成使用类ADD_ACTION钩,加$给你的ADD_ACTION呼叫一起与该类中的函数名,例如:

class MyPluginClass 
{ 
    public function __construct() 
    { 
     //add your actions to the constructor! 
     add_action('save_post', array($this, 'myplugin_save_posts')); 
    } 

    public function myplugin_save_posts() 
    { 
     //do stuff here... 
    } 
}