recently started learning PHP and met with anonymous functions. Can you please explain in which situation it is better to use them? I understand that they are used in order not to litter the global space. And where else can they come in handy? How to understand what exactly in this place need an anonymous function?
2 answers
Anonymous functions are needed (for example) for functions that require a callback function, such as array_map () , array_filter () , array_reduce () .
PS You will find all the possibilities in the documentation, but the meaning is the same: an anonymous function can be used in such situations where the function will be used once.
|
Here, for example, two functions on the definition of the gap. In your opinion, is it better to use an anonymous function? Or look at the circumstances ie. if I only need the function once, then I will use an anonymous function. Right ?
function RangeValidator($min, $max){ return function ($val) use ($min, $max){ // возвращает ф-цию с предустановленными границами return ($val >= $min && $val <= $max) ? true : false; }; } $a = getRangeValidator(5, 10); echo $a(4); __________________________________ function RangeValidator($min, $max, $val){ return ($val >= $min && $val <= $max) ? true : false; } echo RangeValidator(5, 10, 4) I want to understand where and when it is better to use anonymous functions, and when not.
|