是否使用do_action() 或do_action_ref_array(), 对于这两个函数,从钩子回调访问参数是相同的。但它们之间的主要区别在于我们为函数提供参数的方式:
带do_action(), 我们只需分别传递每个参数:
do_action( \'some_hook\', 1, 2, 3, \'etc\' );
// i.e. do_action( <hook name>, <parameter>, <parameter>, <parameter>, ... );
但带有
do_action_ref_array(), 我们将每个参数放入一个数组中,然后将该数组作为第二个参数传递给
do_action_ref_array():
do_action_ref_array( \'some_hook\', array( 1, 2, 3, \'etc\' ) );
/* i.e. do_action_ref_array( <hook name>, array(
<parameter>, <parameter>, <parameter>, ...
) ); */
但尽管存在这种差异,
do_action_ref_array() 将实际将每个数组项作为一个单独的参数传递给挂钩回调,即它执行类似的操作
hook_callback( <parameter>, <parameter>, <parameter>, ... ); e、 g。
my_function( $args[0], $args[1] ) 哪里
my_function 是钩子回调,并且
$args 数组是否传递给
do_action_ref_array().
// Let\'s say you had this:
add_action( \'my_hook\', \'my_function\' );
// And then this:
$args = [ 1, 2 ]; // same as $args = array( 1, 2 )
do_action_ref_array( \'my_hook\', $args );
// And do_action_ref_array would make a call that\'s similar to:
my_function( $args[0] ); // i.e. my_function( 1 )
// But if you had this: (note the fourth parameter)
add_action( \'my_hook\', \'my_function\', 10, 2 );
// Then the call would be:
my_function( $args[0], $args[1] ); // i.e. my_function( 1, 2 )
因此,如果您希望
5 和
6 如果在回调中可用,则回调需要接受两个参数
and 告诉
add_action() (通过第四个
parameter) 要向回调传递两个参数,请执行以下操作:
// Set the callback to accept two parameters.
function testing_ref_array( $arg1, $arg2 ) {
var_dump( $arg1, $arg2 );
}
// And then tell add_action() to pass two parameters to the callback.
add_action( \'testing\', \'testing_ref_array\', 10, 2 );
// i.e. add_action( <hook name>, <callback>, <priority>, <number of accepted parameters> )
此外,值得注意的是
do_action_ref_array() 使用
call_user_func_array() 调用钩子回调,那么我们如何调用
call_user_func_array() 也是我们所说的
do_action_ref_array(), 除了第一个参数
do_action_ref_array() 是挂钩名称,而不是回调。相同的上下文适用于
do_action(), 但它更像
call_user_func(), 尽管如此
do_action() 还使用
call_user_func_array().