开发者

wordpress : add_action : why the second parameter is an array instead of a function name

开发者 https://www.devze.com 2023-03-09 16:09 出处:网络
I am trying to create a wordpress plugin, I found one plugin which use oops concepts, my question is why the second parameter in the add_action function is an array instead of a function name

I am trying to create a wordpress plugin, I found one plugin which use oops concepts, my question is why the second parameter in the add_action function is an array instead of a function name

add_action('admin_menu', array(&$this, 开发者_如何学JAVA'my_menu'));

my_menu is a function in the same class, please help me

Thanks


Because the second argument needs to be a callback. (and add_action internally uses call_user_func_array).

For functions we can just pass its name as a string but we can't do that with object methods, can we?

So an array is passed with 2 elements, first the object and second the method to call:-

array( $object, 'method' )

Oh and you can safely remove that useless '&', PHP4 days are gone now.


@Thomas John, you are correct about second argument in add_action also in wordpress org not mentioned anything about this so now, let me know you, we can pass array as second argument array($this,'method').

Description: when object creates of class then constructor automatically calls and your action performs.

WHY IT REQUIRES in wordpress how to create or initialize the class in add_action method in short add_action referencing a class check below example

class Myclass{
 public function __construct() {


add_action( 'plugins_loaded', array( $this, 'load_plugin_textdomain' ) );

}
}

Referencing a class using add_action().

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号