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()?
3
  • 2
    Use is only available with a closure (stackoverflow.com/questions/1065188/…). But you could always write your own closure to wrap the callback if required. Commented Jun 22, 2021 at 8:53
  • you can reference your outside variable by putting global $myVar,$myVar1; althoug that's not recommended but it's work Commented Jun 22, 2021 at 8:54
  • 2
    @Jerson For the love of god: no! Commented Jun 22, 2021 at 8:56

1 Answer 1

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); })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.