【问题标题】:php inline callbackphp内联回调
【发布时间】:2012-10-02 00:31:37
【问题描述】:

一个简单的问题。

是否可以在 php 中内联声明回调函数?例如,

array_filter($input_array, "function($item) { $item['state'] != 0 }")

【问题讨论】:

    标签: php callback inline


    【解决方案1】:

    是的,在 php 5.3 之后,你可以使用匿名函数了。

    array_filter($input_array, function($item) { return $item['state'] != 0; });
    

    【讨论】:

    • 不幸的是,这不是我的情况.. 5.1 :(
    • @jose 然后你可以使用 create_function php.net/manual/en/function.create-function.php
    • 感谢您分享您的知识!
    • 注意匿名函数内的每一行代码都需要以分号结尾。
    【解决方案2】:

    肯定是调用anonymous functions:

    array_filter($input_array, function($item) { 
        return $item['state'] != 0;
    });
    

    【讨论】:

      【解决方案3】:
      array_filter($input_array, function($item) { 
          return $item['state'] != 0;
      });
      

      此功能从 5.3 或 > 版本的 php 可用。在 5.4> 版本将支持 $this 内联匿名函数

      php回调链接> How do I implement a callback in PHP?

      【讨论】:

      • 这与已接受的答案相同。请避免这样做。
      【解决方案4】:

      使用 create_function? 例如:

       $result = array_filter($array, create_function('$a','return preg_match("#\S#", $a);'));     
      

      【讨论】:

        猜你喜欢
        • 2018-12-01
        • 1970-01-01
        • 2014-03-04
        • 2017-07-21
        • 1970-01-01
        • 1970-01-01
        • 2013-08-17
        • 2013-06-05
        • 2012-01-31
        相关资源
        最近更新 更多