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

I'm trying to create a wordpress plugin, I found one plugin that uses oops concepts, so 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, 'My_menu'));

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

thanks

+8
php wordpress
source share
2 answers

Because the second argument must be callback . (and add_action internally uses call_user_func_array ).

For functions, we can simply pass our name as a string, but we cannot do this using object methods, can we?

So, the array is transmitted with two elements, first an object and a second call method: -

array( $object, 'method' )

Oh, and you can safely remove this useless "&", the days of PHP4 are gone.

+8
source share

@Thomas John, you're right about the second argument in add_action, and nothing is mentioned in wordpress org, so let me know, we can pass the array as the second array of arguments ($ this, 'method').

Description: when an object creates a class, then the constructor automatically calls and your action performs.

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

 class Myclass{ public function __construct() { add_action( 'plugins_loaded', array( $this, 'load_plugin_textdomain' ) ); } } 

Link to the class using add_action ().

0
source share

All Articles