dqpciw9742
2017-08-02 12:25
浏览 28
已采纳

php警告:{closure}()缺少参数2

I have encountered a warning I am not understanding, and I'd like to know in which way this may affect my code. As far as I can tell, the code works and everything looks like it should. I am working in a WordPress setting, however it seems to me that the problem is a misunderstanding on how to use anonymous function, and not strictly related to WordPress. However, this is the situation. I have a class with a few methods creating standard pages, which I need to repeat for several instances of that class. The class methods return the content of the page and they work correctly. I want to add these pages to the wordpress admin menu, and normally I would simply call the function

 $t = new My_Class();
 //the method of the class that generates the content 
 $function_name = "foo";
 add_submenu_page( $parent_slug,  $title, $menu_title , 'manage_options', $function_name, array( $t, $function_name) ); 

However, in this case the function returns the content instead of echoing it, so that would result in a blank page. So I tried this

 add_submenu_page( $parent_slug,  $title, $menu_title , 'manage_options', $function_name, function ($t, $function_name ) use ($t, $function_name) {
        echo $t->$function_name();
    } );    

As I said, this works, but it generates that warning and it made me wonder if I am doing something wrong or if I am misunderstanding what the code is doing (thus potentially leading to unwanted behaviours in the future).

PS: I KNOW I could simply add a new method that echoes the content of the other one, or add a parameter to echo the content instead of returning it. However, I'd rather understand what the problem is, if any.

图片转代码服务由CSDN问答提供 功能建议

我遇到了一个我不理解的警告,我想知道这可能影响我的方式 码。 据我所知,代码工作,一切看起来应该如此。 我正在使用WordPress设置,但在我看来,问题是对如何使用匿名函数的误解,而不是与WordPress严格相关。 但是,这就是情况。 我有一个类,有几个方法创建标准页面,我需要重复该类的几个实例。 类方法返回页面的内容并且它们正常工作。 我想将这些页面添加到wordpress管理菜单中,通常我只需要调用函数

  $  t = new My_Class(); 
 //生成内容的类的方法
 $ function_name =“foo”; 
 add_submenu_page($ parent_slug,$ title,$ menu_title,'manage_options',$ function_name,array  ($ t,$ function_name));  
   
 
 

但是,在这种情况下,函数返回内容而不是回显内容,因此会导致空白页面。 所以我尝试了这个

  add_submenu_page($ parent_slug,$ title,$ menu_title,'manage_options',$ function_name,function($ t,$ function_name)use($ t,$  function_name){
 echo $ t-> $ function_name(); 
});  
   
 
 

正如我所说,这是有效的,但它产生了警告,这让我想知道我做错了什么,或者我是否误解了代码在做什么 (因此可能导致将来出现不需要的行为)。

PS:我知道我可以简单地添加一个回应另一个内容的新方法,或添加一个参数来回显 内容而不是返回它。 但是,我宁愿明白问题是什么,如果有的话。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题