What use is lambda in PHP?

后端 未结 5 1723
南方客
南方客 2020-12-12 21:40

The lambda anonymous function is part of PHP 5.3. What use does it have? Is there anything that one can only do with lambda? Is lambda better for certain tasks?

I\'

5条回答
  •  半阙折子戏
    2020-12-12 22:27

    Anything that requires a temporary function that you probably will only use once.

    I would use them for callbacks, for functions such as:

    • usort
    • preg_replace_callback

    E.g.

    usort($myArray, function ($a, $b) {
        return $a < $b;
    });
    

    Before 5.3, you'd have to..

    function mySort ($a, $b) {
        return $a < $b;
    }
    usort($myArray, 'mySort');
    

    Or create_function ...

    usort($myArray, create_function('$a, $b', 'return $a < $b;'));
    

提交回复
热议问题