將頁面添加到您使用的 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'] ) );}幫助將不勝感激!
1 回答

紅顏莎娜
TA貢獻1842條經驗 獲得超13個贊
您應該能夠傳遞一個匿名函數,其函數體將簡單地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 非常不熟悉,所以這可能不是最合適的方法。
- 1 回答
- 0 關注
- 106 瀏覽
添加回答
舉報
0/150
提交
取消