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

  1. snowrui August 20, 2008 / 9:34 am

    是感觉语法有点怪怪的

  2. Leo the Tiger August 3, 2008 / 1:11 pm

    你的博客在GOOGLE中“神仙”关键字已经被挤到第二页了

  3. gaogao August 1, 2008 / 7:39 pm

    …………好难

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s