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?

JavaScript

…does not work

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

JavaScript

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.

JavaScript

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

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