PHP5.3将加入闭包语法
PHP 5.3 将加入闭包语法,也就是匿名函数,允许开发者申明行内函数和在变量中保存。虽然这个语法和JavaScript的闭包相比有点怪异,但是对于PHP语言来说,这是一个良好的补充。比如你现在就可以这样使用:
Php代码
- $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; };
$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代码
- function item_list(array $items, $formatter = null) {
- //create the default formatter
- if($formatter == null) {
- $formatter = function($row) {
-
return '
'
. $row . ''; - };
- }
-
$html = '
Listing:
'; - foreach($items as $item) {
- $html .= $formatter($item);
- }
- return $html;
- }
PHP之友评论