将页面添加到您使用的 WordPress 管理员时add_menu_page
,它接受可调用的函数/方法。
class Foo
{
public function __construct()
{
add_menu_page($page_title, $menu_title, $capability, $menu_slug, [$this, 'bar'], $icon_url, $position);
}
public function bar(): void
{
echo 'Hello, World!';
}
}
我的问题是,我对如何在接受/期望参数时传递参数感到有点困惑bar,例如:
class Foo
{
public function __construct()
{
add_menu_page($page_title, $menu_title, $capability, $menu_slug, [$this, 'bar'], $icon_url, $position);
}
public function bar(string $name = ''): void
{
echo "Hello, {$name}!";
}
}
我尝试了几种不同的方法,但似乎无法让它发挥作用:
[$this, 'bar', 'Bob']; // Warning: call_user_func_array() expects parameter 1 to be a valid callback, array must have exactly two members in /wp-includes/class-wp-hook.php on line 287
[$this, ['bar', 'Bob']] // Warning: call_user_func_array() expects parameter 1 to be a valid callback, second array member is not a valid method in /wp-includes/class-wp-hook.php on line 287
所以看看该文件的第 287 行,它正在使用call_user_func_array,我认为似乎可以在 的$function参数中传递一个参数add_menu_page,但我就是无法让它工作:
// Avoid the array_slice() if possible.
if ( 0 == $the_['accepted_args'] ) {
$value = call_user_func( $the_['function'] );
} elseif ( $the_['accepted_args'] >= $num_args ) {
$value = call_user_func_array( $the_['function'], $args );
} else {
$value = call_user_func_array( $the_['function'], array_slice( $args, 0, (int) $the_['accepted_args'] ) );
}
帮助将不胜感激!
红颜莎娜