create_function()是PHP中的内置函数,用于在PHP中创建匿名(lambda样式)函数。
null
语法:
string create_function ( $args, $code )
参数: 此函数接受以下两个参数:
- $args: 它是一个字符串类型的函数参数。
- $code: 这是一个字符串类型的函数代码。
注: 通常,这些参数将作为单引号分隔的字符串传递。使用单引号字符串的原因是为了保护变量名不被解析,否则,将需要双引号来转义变量名,例如$avar。
返回值: 此函数以字符串形式返回唯一的函数名,否则出错时返回FALSE。
下面的程序演示了PHP中的create_function()函数:
项目1: 使用create_function()创建匿名函数
<?php //create a function from information // gathered at run time, $newfunc = create_function( '$a, $b' , ' return "ln($a) + ln($b) = " . log( $a * $b );'); echo "New anonymous function: $newfunc" ; echo $newfunc (2, M_E) . "" ; ?> |
输出:
New anonymous function: lambda_1 ln(2) + ln(2.718281828459) = 1.6931471805599
项目2: 使用Create_function()创建常规函数
<?php // General function that can apply a set of // operations to a list of parameters. function Program( $value1 , $value2 , $arr ) { foreach ( $arr as $val ) { echo $val ( $value1 , $value2 ) . "" ; } } // create a bunch of math functions $f1 = ' if ( $a >= 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" . "Parameter is a = 2 and b = 3" ; 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 "Second array of anonymous functions" . "Parameter is a = GeeksForGeeks and" . "b = GeeksForGeeks" ; 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/manual/en/function.create-function.php
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END