How to use arrow functions in PHP?

前端 未结 2 610
名媛妹妹
名媛妹妹 2021-02-08 05:38

I got to know about arrow functions in PHP 7.4. I tried using them like

 {
           


        
2条回答
  •  既然无缘
    2021-02-08 06:19

    The arrow functions can make your code shorter and more readable in some situations. They were primarily designed with a thought of using them for simple callbacks. As an example consider usort() which takes in a callback function as a user parameter.

    Prior to PHP 7 you had to do something like this to define your own callback for usort():

    // old syntax prior to PHP 7
    function cmp($a, $b) {
        if ($a == $b) {
            return 0;
        }
        return ($a < $b) ? -1 : 1;
    }
    
    $a = [3, 2, 5, 6, 1];
    
    usort($a, "cmp");
    
    foreach ($a as $key => $value) {
        echo "$key: $value\n";
    }
    

    PHP 7 has added a spaceship operator and now thanks to arrow functions you can make your code much cleaner.

    // New syntax since PHP 7.4
    $a = [3, 2, 5, 6, 1];
    
    usort($a, fn($a, $b) => $a<=>$b);
    
    foreach ($a as $key => $value) {
        echo "$key: $value\n";
    }
    

    Try it online at 3v4l.org

    Anonymous functions in PHP can be quite verbose, even when they only perform a simple operation, hence the reason for a shorter syntax. As another example consider the following function:

    // Returns an array with each element squared - old syntax
    function array_square($arr) {
        return array_map(function($x) { return $x*$x; }, $arr);
    }
    
    // Returns an array with each element squared - new syntax
    function array_square($arr) {
        return array_map(fn($x) => $x**2, $arr);
    }
    
    print_r(array_square([1,2,3,4,5]));
    

    Reducing the unnecessary syntax helps to understand the real purpose of the code, but keep in mind that shorter does not always mean cleaner! I would recommended to treat arrow functions with the same caution as ternary operators. Only use them when you know it helps readability, not just to make your code shorter.

提交回复
热议问题