代码之家  ›  专栏  ›  技术社区  ›  Kirzilla

为什么以及如何在PHP中使用匿名函数?

  •  44
  • Kirzilla  · 技术社区  · 15 年前

    匿名函数可从php 5.3获得。
    我应该使用它们还是避免使用它们?如果是,如何?

    编辑 ;刚刚发现了一些PHP匿名函数的好技巧…

    $container           = new DependencyInjectionContainer();
    $container->mail     = function($container) {};
    $conteiner->db       = function($container) {};
    $container->memcache = function($container) {};
    
    6 回复  |  直到 7 年前
        1
  •  86
  •   Gumbo    15 年前

    Anonymous functions 在使用需要 callback function 喜欢 array_filter array_map 做:

    $arr = range(0, 10);
    $arr_even = array_filter($arr, function($val) { return $val % 2 == 0; });
    $arr_square = array_map(function($val) { return $val * $val; }, $arr);
    

    否则,您需要定义一个可能只使用一次的函数:

    function isEven($val) { return $val % 2 == 0; }
    $arr_even = array_filter($arr, 'isEven');
    function square($val) { return $val * $val; }
    $arr_square = array_map('square', $arr);
    
        2
  •  23
  •   salathe    15 年前

    匿名函数可从php 5.3获得。

    匿名函数在PHP中已经存在很长时间了: create_function 从php 4.0.1开始就存在。不过,从PHP5.3开始就有了一个新的概念和语法,这是非常正确的。

    我应该使用它们还是避免使用它们?如果是,如何?

    如果你曾经用过 create_function 在此之前,新的语法可以直接滑入您使用它的地方。正如其他答案所提到的,一个常见的情况是对于“一次性”函数,它们只使用一次(或至少在一个地方)。通常以回调的形式出现 array_map / reduce / filter , preg_replace_callback , usort 等等。

    使用匿名函数计算字母在单词中出现的次数的示例(这可以通过许多其他方式实现,只是一个示例):

    $array = array('apple', 'banana', 'cherry', 'damson');
    
    // For each item in the array, count the letters in the word
    $array = array_map(function($value){
        $letters = str_split($value);
        $counts  = array_count_values($letters);
        return $counts;
    }, $array);
    
    // Sum the counts for each letter
    $array = array_reduce($array, function($reduced, $value) {
        foreach ($value as $letter => $count) {
            if ( ! isset($reduced[$letter])) {
                $reduced[$letter] = 0;
            }
            $reduced[$letter] += $count;
        }
        return $reduced;
    });
    
    // Sort counts in descending order, no anonymous function here :-)
    arsort($array);
    
    print_r($array);
    

    这给(剪短为简洁):

    Array
    (
        [a] => 5
        [n] => 3
        [e] => 2
        ... more ...
        [y] => 1
    )
    
        3
  •  9
  •   animuson    15 年前

    也许你可以读一下PHP的文章 Anonymous Functions . 其实很不错。

        4
  •  4
  •   brasofilo Gary    11 年前

    匿名函数在将函数创建到DI容器中也非常有用,例如“bootstrap.php”:

    //add sessions
    $di->add("session",function(){ return new Session(); });
    //add cache
    $di->add("cache",function(){ return new Cache(); });
    //add class which will be used in any request
    $di->add("anyTimeCalledClass", new SomeClass());
    

    使用参数和下一个变量的示例

    $di->add("myName",function($params) use($application){
          $application->myMethod($params);
    });
    

    在这里,您可以看到如何使用匿名函数来保存内存和服务器负载。您可以在 di 容器,但实例将在需要时创建。

        5
  •  2
  •   Toby Allen mercator    13 年前

    匿名函数的典型用法是回调函数。例如,可以使用它们从排序算法(如in函数)中回调 uksort ( http://lv.php.net/uksort )或替换算法,如 preg_replace_callback ( http://lv.php.net/manual/en/function.preg-replace-callback.php ) 我自己没有在PHP中尝试过,所以这只是一个猜测。

        6
  •  0
  •   devquora    7 年前

    下面是在PHP中使用匿名函数的示例

    $suppliers=['add1'=>'nodia','add2'=>'delhi', 'add3'=>'UP'];
     $getAddress = function($suppliers){ $address=[];
     for($i=1;$i<5;$i++){
      if(array_key_exists('add'.$i, $suppliers))
        $address[]=$suppliers['add'.$i];
      }
     return $address;};
     print_r($getAddress($suppliers));
    

    在上面的例子中,我们编写了匿名函数来检查输入数组中是否存在键。如果它存在,那么它将把它放入输出数组中。