Fil*_*erg 15
PHP.net有一个关于匿名函数的手册页,在Wikipedia上你可以阅读一般的匿名函数.
匿名函数可用于包含不需要命名的功能,也可能用于短期使用.一些值得注意的例子包括闭包.
来自PHP.net的示例
<?php
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};
$greet('World');
$greet('PHP');
?>
Run Code Online (Sandbox Code Playgroud)
PHP 4.0.1到5.3
$foo = create_function('$x', 'return $x*$x;');
$bar = create_function("\$x", "return \$x*\$x;");
echo $foo(10);
Run Code Online (Sandbox Code Playgroud)
PHP 5.3
$x = 3;
$func = function($z) { return $z *= 2; };
echo $func($x); // prints 6
Run Code Online (Sandbox Code Playgroud)
PHP 5.3确实支持闭包,但必须明确指出变量
$x = 3;
$func = function() use(&$x) { $x *= 2; };
$func();
echo $x; // prints 6
Run Code Online (Sandbox Code Playgroud)
从维基百科和php.net采取的示例