2

将页面添加到您使用的 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'] ) );
}

帮助将不胜感激!

4

1 回答 1

1

您应该能够改为传递一个匿名函数,其主体将简单地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 非常陌生,因此这可能不是最合适的方法。

于 2020-08-05T06:20:28.393 回答