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.

 

相关文章:

  • 2023-03-11
  • 2022-12-23
  • 2022-12-23
  • 2022-02-22
  • 2022-12-23
  • 2022-12-23
  • 2021-08-14
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-01-07
  • 2021-12-02
  • 2021-10-25
相关资源
相似解决方案