Pass parameters to an anonymous function with help from the use keyword in PHP


Sometimes we have to use anonymous functions (you can read this answer from Stack Overflow to get an understanding of, when you have to use anonymous functions).

But sometimes it can give some problems when you want to pass parameters to the function. The best solution, that I have found until now, is to use the keyword use. You can see this blog post about the use keyword.

When do I use the use keyword?

I can give you some examples of, when to use the use keyword.

Example 1: advanced queries and eager loading in Laravel - with sorting based on user inputs

I wrote a blog post about advanced quires and eager loading in Laravel, two days ago. In this blog post, I did use an anonymous function to create advanced quires for the with function in Laravel. Later on that project, I came across another problem. I had to add sorting to the query, based on inputs from the user. So I had to use some other parameters, than the standard $query. I added the use keyword - really simple solution to the problem:

$users = User::with(array(
   'comments' => function($query) use($sort, $order) {
      $query->where('likes', '>', 10)->orderBy($sort, $order);
))->orderBy('username', 'desc')->limit(10)->get();

Example 2: Parsing extra parameters to a filter in WordPress

Another example is when you have to use a filter in WordPress, and want some extra parameters.

In a project I did for a customer, I had to pass extra parameters to a filter. WordPress has no good way to do that, so I had to use an anonymous function and then add the use keyword with my parameter.

add_filter('woocommerce_shortcode_products_query', function($args) use($per_page){
   return $this->modify_products_query($args, $per_page);

Martin Schadegg Rasch Jensen