PHP中的匿名函数是什么?你能给我一个简单的例子吗?
答案 0 :(得分:15)
PHP.net有一个关于Anonymous functions的手册页,在维基百科上,你可以阅读Anonymous functions一般。
匿名函数可用于包含不需要命名且可能用于短期使用的功能。一些值得注意的例子包括闭包。
来自PHP.net的示例
<?php
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};
$greet('World');
$greet('PHP');
?>
PHP 4.0.1到5.3
$foo = create_function('$x', 'return $x*$x;');
$bar = create_function("\$x", "return \$x*\$x;");
echo $foo(10);
PHP 5.3
$x = 3;
$func = function($z) { return $z *= 2; };
echo $func($x); // prints 6
PHP 5.3支持闭包,但必须明确指出变量
$x = 3;
$func = function() use(&$x) { $x *= 2; };
$func();
echo $x; // prints 6
来自维基百科和php.net的示例
答案 1 :(得分:1)
Google的第一个结果为您提供了答案:
http://php.net/manual/de/functions.anonymous.php
echo preg_replace_callback('~-([a-z])~', function ($match) {
return strtoupper($match[1]);
}, 'hello-world');
// outputs helloWorld
您使用函数作为参数(在此示例中)是“匿名函数”。匿名,因为您没有像“正常”那样明确声明该函数。
function foo($match) {
return strtoupper($match[1]);
}