Home > Software design >  php initialize "use" variable for anonymous function / closure
php initialize "use" variable for anonymous function / closure

Time:05-28

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

CodePudding user response:

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

  • Related