PHP | create_function()函数
该create_function()是PHP的内置函数用于创建的PHP匿名(λ-风格)函数。
句法:
string create_function ( $args, $code )
参数:此函数接受两个参数,如下所述:
- $args:它是一个字符串类型的函数参数。
- $code:它是一个字符串类型的函数代码。
注意:通常,这些参数将作为单引号分隔的字符串传递。使用单引号字符串的原因是为了保护变量名不被解析,否则需要双引号来转义变量名,例如\$avar。
返回值:此函数以字符串返回唯一的函数名称,否则在出错时返回 FALSE。
下面的程序说明了PHP的 create_function()函数:
程序 1:使用 create_function() 创建匿名函数
输出:
New anonymous function: lambda_1
ln(2) + ln(2.718281828459) = 1.6931471805599
程序2:用create_function()创建一个通用函数
= 0) { return "b * a^2 = ".
$b * sqrt($a);} else { return false; }';
$f2 = "return \"min(a, b) = \".min(\$a, \$b);";
$farr = array(
create_function('$x, $y', 'return
"a hypotenuse: ".sqrt($x * $x + $y * $y);'),
create_function('$a, $b', $f1),
create_function('$a, $b', $f2)
);
echo "first array of anonymous functions" .
"\nParameter is a = 2 and b = 3\n";
Program(2, 3, $farr);
// now make a bunch of string functions
$sarr = array(
create_function('$a, $b', 'return
"Lower case : " . strtolower($a) ;'),
create_function('$a, $b', 'return
"Similar Character : " .
similar_text($a, $b, $percent);')
);
echo "\nSecond array of anonymous functions" .
"\nParameter is a = GeeksForGeeks and" .
"b = GeeksForGeeks\n";
Program("GeeksForGeeks", "GeeksForGeeks", $sarr);
?>
输出:
first array of anonymous functions
Parameter is a = 2 and b = 3
a hypotenuse: 3.605551275464
b * a^2 = 4.2426406871193
min(a, b) = 2
Second array of anonymous functions
Parameter is a = GeeksForGeeks andb = GeeksForGeeks
Lower case : geeksforgeeks
Similar Character : 13
参考文献:HTTP:// PHP.NET /手动/ EN /函数.create功能。 PHP