PHP 5.3.4 的闭包: function() use(&$param)

PHP 的变量作用域是函数级的,没有层级作用域

5.3.4 增加了闭包:

1、可以用变量引用函数

2、可以声明匿名函数

3、可以使用函数作为 函数的参数和返回值 

4、声明函数时可以使用 use($param)  来向函数中传入函数外的变量,结合变量引用来实现闭包

 

function closureCreater(){
$x =1;
return function($fun=null) use(&$x){//按引用传值
echo "<br />".$x++;
$fun and $fun();
};
}

 

$x = "hello world";
$test = closureCreater();
$test();
$test(function(){ echo "closure test one"; });
$test(function(){ echo "closure test two"; });
$test(function() use($x){ echo "<br />".$x;});
 

//将函数保存为数组元素
$x = 'outer param.';
$arr = array();
$arr[] = function($str)use($x){ return $str.$x; };
echo $arr[0]('test fun in arr,');  //test fun in arr,outer param.

 

posted @ 2012-12-05 02:00  ecalf  阅读(1431)  评论(0编辑  收藏  举报