PHP 中的匿名函数是什么?请给我一个简单的例子好吗?
最佳答案
PHP.net 有一个关于 Anonymous functions 的手册页在维基百科上,您可以阅读有关 Anonymous functions 的信息一般而言。
Anonymous functions can be used to contain functionality that need not be named and possibly for short-term use. Some notable examples include closures.
来自 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 does support closures but the variables must be explicitly indicated
$x = 3;
$func = function() use(&$x) { $x *= 2; };
$func();
echo $x; // prints 6
示例取自维基百科和 php.net
关于php - 什么是 PHP 匿名函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3698553/