Skip to content
Advertisement

php initialize “use” variable for anonymous function / closure

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”.

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement