Robbert
Robbert

Reputation: 1330

Array filter callback reference with use()

I am wondering how I can use a combination of the use() method and a reference to a callback:

array_filter($array, function($value) use($external_parameter) {
   // Return ...
}); 

How can I include the use() method together with a reference to a callback?

array_filter($array, 'custom_callback_function'); // Where use()?

Upvotes: 0

Views: 177

Answers (1)

deceze
deceze

Reputation: 522135

You would need to include the use in the function declaration, like:

function foo() use ($bar) { ... }

But that doesn't actually work, because a) it's syntactically not supported, and b), logically, you don't know the variable name at the time, and it's probably not in scope at that time anyway. At best your function can accept an additional parameter:

function foo($bar, $baz) { ... }

And you capture a variable and pass it to foo like this:

array_filter($array, function (...$args) use ($bar) { return foo($bar, ...$args); })

Upvotes: 2

Related Questions