什么是PHP匿名函数?

什么是PHP匿名函数?,php,Php,什么是PHP中的匿名函数?你能给我一个简单的例子吗?PHP.net有一个关于维基百科的手册页面,你可以在上面阅读 匿名函数可用于包含不需要命名的功能,并且可能用于短期使用。一些值得注意的例子包括闭包 来自PHP.net的示例 <?php $greet = function($name) { printf("Hello %s\r\n", $name); }; $greet('World'); $greet('PHP'); ?> PHP5.3 $foo = create_fu

什么是PHP中的匿名函数?你能给我一个简单的例子吗?

PHP.net有一个关于维基百科的手册页面,你可以在上面阅读

匿名函数可用于包含不需要命名的功能,并且可能用于短期使用。一些值得注意的例子包括闭包

来自PHP.net的示例

<?php
$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};

$greet('World');
$greet('PHP');
?>
PHP5.3

$foo = create_function('$x', 'return $x*$x;');
$bar = create_function("\$x", "return \$x*\$x;");
echo $foo(10);
$x = 3;
$func = function($z) { return $z *= 2; };
echo $func($x); // prints 6
PHP5.3确实支持闭包,但必须明确指出变量


来自维基百科和php.net的示例Google的第一个结果为您提供了答案:

使用函数作为参数(在本例中)是一个“匿名函数”。匿名,因为您没有像“正常”那样显式声明函数


虽然我写PHP已经多年了,但它不知道这是可能的!Nice.PHP不支持咖喱(至少在本机上是不支持的)@Nils它从5.3.0开始就存在了,所以它是一种新的@NullUserException,引用了我找到的最好的解释,删除了咖喱部分。同样
在4.0.1之前,PHP没有匿名函数支持。
,所以它不是很新。但是5.3中的不同(更好)语法。如果我们可以这样做,它会更棒:$x=function($y){return$y*2;}($z);
$x = 3;
$func = function() use(&$x) { $x *= 2; };
$func();
echo $x; // prints 6
echo preg_replace_callback('~-([a-z])~', function ($match) {
    return strtoupper($match[1]);
}, 'hello-world');
// outputs helloWorld
function foo($match) {
 return strtoupper($match[1]);
}