DavidTonarini
DavidTonarini

Reputation: 951

php Warning: Missing argument 2 for {closure}()

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.

Upvotes: 1

Views: 2791

Answers (1)

Sasa Blagojevic
Sasa Blagojevic

Reputation: 2200

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

Upvotes: 1

Related Questions