2013-03-01 17 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... 
    } 
}