1

Is there a neat way to initialize a variable used in a closure?

function() use($v = 0) { echo ++$v }

...does not work

An example use case is for array_reduce where we might want to count the array elements...

echo array_reduce(['a', 'b', 'c'], function($output, $item) use(&$count) { return $output . ++$count . '. ' . $item . "\n"; }, '');

This will work - declaring $count by reference and incrementing from null will not yield an error - but I don't think this is "good practice".

1
  • If you can't incorporate it to the callback signature, you're essentially introducing a global variable in a function that causes side effects elsewhere. I can't think of a clean solution to that; the use statement at least makes it explicit. Commented May 27, 2022 at 12:25

1 Answer 1

1

You could use a static variable that is initialized once.

echo array_reduce(['a', 'b', 'c'], function($output, $item) { static $count = 0; return $output . ++$count . '. ' . $item . "\n"; }, '');

Demo: https://3v4l.org/D0Nv2

Sign up to request clarification or add additional context in comments.

3 Comments

Awesome, thank you :-) This is really neat and I expect there is little or no performance impact - php simply skips over the line of subsequent iterations? I will implement it right now :-)
@lm713 This variable is internal to the function, you can't read it from outside. It might be what you really had in mind from the beginning, but it's worth noting that it isn't really an alternative implementation but something different.
@ÁlvaroGonzález thank you - yes you are right, it is not exactly what I had in mind, but it seems to be the closest thing available and suitable for the example use case, so I will leave it as the accepted answer until PHP make something like use($v=0) possible. On the other hand, if $v is required in the parent scope, I would argue that initializing it outside the closure declaration is not so messy.

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.