dry18813 2010-07-25 13:36
浏览 59
已采纳

我如何使用PHP 5.3 Closures,比如我们在Ruby中使用Blocks

How can I use PHP 5.3 Closures like We use Blocks in Ruby. I never used 'for' Loop in Ruby due to using Blocks with 'each' 'find_all' 'inject' Methods.

How can I use PHP 5.3 Closures like Ruby Blocks and say bye-bye to 'for' Loops :)

Like Between { and } is a Closure(or Block or Anonymous Function)

fruit = %w[apple banana orange]
fruit.each { |f| print "#{f}, " }

I do it in PHP this way,

$fruit = array('apple', 'banana', 'orange');
foreach ($fruit as $f) 
{
 print "$f, "; 
}

Is there a way to do this the Ruby way using PHP Closures as PHP 5.3 supports it.

  • 写回答

4条回答 默认 最新

  • doushou7169 2010-07-25 14:20
    关注

    If you are looking at using lambdas to iterate over a PHP array, there are certain functions that you could use to accomplish that. Better illustrate it, I used a wrapper class enum:

    class enum {
        public $arr;
    
        function __construct($array) {
            $this->arr = $array;
        }
    
        function each($lambda) {
            array_walk($this->arr, $lambda);
        }
    
        function find_all($lambda) {
            return array_filter($this->arr, $lambda);
        }
    
        function inject($lambda, $initial=null) {
            if ($initial == null) {
                $first = array_shift($this->arr);
                $result = array_reduce($this->arr, $lambda, $first);
                array_unshift($this->arr, $first);
    
                return $result;
            } else {
                return array_reduce($this->arr, $lambda, $initial);
            }
        }
    
    }
    
    
    $list = new enum(array(-1, 3, 4, 5, -7));
    $list->each(function($a) { print $a . "
    ";});
    
    // in PHP you can also assign a closure to a variable 
    $pos = function($a) { return ($a < 0) ? false : true;};
    $positives = $list->find_all($pos);
    
    // inject() examples
    $list = new enum(range(5, 10));
    
    $sum = $list->inject(function($sum, $n) { return $sum+$n; });
    $product = $list->inject(function($acc, $n) { return $acc*$n; }, 1);
    
    $list = new enum(array('cat', 'sheep', 'bear'));
    $longest = $list->inject(function($memo, $word) {
            return (strlen($memo) > strlen($word)) ? $memo : $word; }
        );
    

    That being said, closures in PHP aren't meant to replace the for loop nor do they behave like ruby blocks.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看