将 class、方法和参数传递给 WordPress 函数

Passing a class, method and arguments to WordPress functions

向 WordPress 管理员添加页面时,您使用 add_menu_page,它接受可调用的 function/method。

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!';
    }
}

我的问题是,当 accepts/expects 参数时,我对如何将参数传递给 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 我认为似乎可以在 add_menu_page$function 参数中传递一个参数,但我只是无法让它工作:

// 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'] ) );
}

不胜感激!

您应该能够传递一个 anonymous function,它的主体将使用适当的参数简单地调用 bar 方法。

匿名函数如下所示:

function () { $this->bar('Bob'); }

或者,如果您使用的是 PHP 7.4+:

fn() => $this->bar('Bob')

所以,只需将其作为回调传递,如下所示:

add_menu_page(
  $page_title,
  $menu_title,
  $capability,
  $menu_slug,
  // fn() => $this->bar('Bob'),
  function () {  
    $this->bar('Bob');  
  },
  $icon_url,
  $position
);

注意:我对 WordPress 非常陌生,所以这可能不是最合适的方法。