51CTO推荐:PHP+MySQL视频教程
PHP 5.3 将加入闭包语法,也就是匿名函数,允许开发者申明行内函数和在变量中保存。虽然这个语法和JavaScript的闭包相比有点怪异,但是对于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; }; |
比如在输出HTML中闭包很有用:
function item_list(array $items, $formatter = null) { //create the default formatter if($formatter == null) { $formatter = function($row) { return '﹤p﹥' . $row . '﹤/p﹥'; }; } $html = '﹤h2﹥Listing:﹤/h2﹥'; foreach($items as $item) { $html .= $formatter($item); } return $html; } |
【编辑推荐】