PHP 5.3闭包语法就是一个匿名函数,它可以为开发者带来很多不同的体验。本文就介绍了它的几种使用方法。它与JavaScript的闭包相比稍微有点不同,不过,相对于比如你现在就可以这样使用PHP 5.3闭包语法
- $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; };
比如PHP 5.3闭包语法在输出HTML中闭包很有用:
- function item_list(array $items, $formatter = null) {
-
-
if($formatter == null) {
-
$formatter = function($row) {
-
return '
'
. $row . '';
- };
- }
-
-
$html = '
Listing:
';
-
foreach($items as $item) {
-
$html .= $formatter($item);
- }
-
-
return $html;
- }
以上就是本文介绍的两种不同的PHP 5.3闭包语法的使用,希望对大家有所帮助。
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn