0

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()?
Robbert
  • 1,270
  • 6
  • 30
  • 62
  • 2
    Use is only available with a closure (https://stackoverflow.com/questions/1065188/in-php-what-is-a-closure-and-why-does-it-use-the-use-identifier). But you could always write your own closure to wrap the callback if required. – Nigel Ren Jun 22 '21 at 08:53
  • you can reference your outside variable by putting global $myVar,$myVar1; althoug that's not recommended but it's work – Jerson Jun 22 '21 at 08:54
  • 2
    @Jerson For the love of god: no! – deceze Jun 22 '21 at 08:56

1 Answers1

2

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); })
deceze
  • 510,633
  • 85
  • 743
  • 889