php5.3的closure

之前还抱怨过php没有closure,只能凑活一下,结果前些天就看到5.3已经将closure加入了。php5.3的变化还真是大,看todo里的future release,那又是许多NB的功能。

先说说closure,最简单的说,就是匿名函数。

还是那个例子:

class ArrayList {
    private $arr;
    function __construct($arr) {
        $this->arr = $arr;
    }

    function each($call) {
        foreach ($this->arr as $item) {
            $call($item);
        }
    }
}
$arr = new ArrayList(array(1,2,3));
$arr->each(function ($item) {
    echo “[$item]n”;
});

真的闭包确实要比假闭包要漂亮多了

当然闭包不仅仅是个匿名函数,还要能够跨越定义和调用处的作用域。这方面,这次php5.3的实现要比javascript的闭包要清晰些,不过语法也就显得有些奇怪。

看例子:

function foo($prefix) {
    return functioin ($s) use ($prefix) {
        return $prefix . $s;
    }
}
$f1 = foo(‘test’);
print_r(array_map($f1, array(‘A’, ‘B’, ‘C’)));
$f2 = foo(‘hello’);
print_r(array_map($f2, array(‘A’, ‘B’, ‘C’)));

3 thoughts on “php5.3的closure

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.