PHP头条
热点:

PHP5.3将加入闭包语法


PHP 5.3 将加入闭包语法,也就是匿名函数,允许开发者申明行内函数和在变量中保存。虽然这个语法和JavaScript的闭包相比有点怪异,但是对于PHP语言来说,这是一个良好的补充。

比如你现在就可以这样使用:

Php代码
  1. $closure = function($param) { echo $param; }; 
  2.   
  3. //This one takes value of someVar and "stores" it in the closure's scope even if 
  4. //we later change the value of someVar outside it. We assume that $somerVar is defined before this 
  5. $closure2 = function($param) use ($someVar) { echo $param . ' ' . $someVar; }; 
$closure = function($param) { echo $param; };
 
//This one takes value of someVar and "stores" it in the closure's scope even if
//we later change the value of someVar outside it. We assume that $somerVar is defined before this
$closure2 = function($param) use ($someVar) { echo $param . ' ' . $someVar; };


比如在输出HTML中闭包很有用:

Php代码
  1. function item_list(array $items, $formatter = null) { 
  2.   //create the default formatter 
  3.   if($formatter == null) { 
  4.     $formatter = function($row) { 
  5.       return '

    ' . $row . '

    '
  6.     }; 
  7.   } 
  8.   
  9.   $html = '

    Listing:

    '
  10.   foreach($items as $item) { 
  11.     $html .= $formatter($item); 
  12.   } 
  13.   
  14.   return $html

www.phpzy.comtrue/phpzx/6235.htmlTechArticlePHP5.3将加入闭包语法 PHP 5.3 将加入闭包语法,也就是匿名函数,允许开发者申明行内函数和在变量中保存。虽然这个语法和JavaScript的闭包相比有点怪异,但是对于PHP语言来说,这是一个...

相关文章

相关频道:

PHP之友评论

今天推荐