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

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.

  • 写回答

1条回答 默认 最新

  • duanba2001 2017-08-02 13:00
    关注

    To get rid of the error message do this

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

    I'm not familiar with WP so I don't know what add_submenu_page() does but it seems that it passes one argument to the anonymous function, which you overwrite by adding the same named $t to the anonymous function lexical scope with use ($t, $function_name).

    Essentially, second argument to function ($t, $function_name) is not being passed, but in the end it works because you have same variable names, and you overwrite them with the variables 'injected' with the use keyword

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器