我如何使用PHP 5.3闭包像我们在Ruby中使用块 [英] How can I use PHP 5.3 Closures like We use Blocks in Ruby
问题描述
如何使用PHP 5.3 Closures,如我们在Ruby中使用Blocks。
我从来没有使用过'Ruby'中的Loop,因为使用了'each''find_all''inject'方法。
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.
如何使用PHP 5.3闭起来像Ruby块,再说再见for循环:)
How can I use PHP 5.3 Closures like Ruby Blocks and say bye-bye to 'for' Loops :)
Like Between {和}之间是一个Closure(或块或匿名函数)
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, ";
}
有一种方法可以使用PHP Closures支持它。
Is there a way to do this the Ruby way using PHP Closures as PHP 5.3 supports it.
推荐答案
如果你正在使用lambdas来遍历PHP数组,你可以使用某些函数以实现这一点。更好地说明它,我使用了一个包装类 enum
:
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 . "\n";});
// 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; }
);
话虽如此,PHP中的闭包不意味着替换for循环,红宝石块。
That being said, closures in PHP aren't meant to replace the for loop nor do they behave like ruby blocks.
这篇关于我如何使用PHP 5.3闭包像我们在Ruby中使用块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!