PHP Create_function ()

PHP

Syntax:
string create_function ($args, $code) 
Parameters:This function takes two parameters, which are described below:
  • $args:is a function argument of a string type.
  • $code:is a function code string type.
Note.Typically these parameters are passed as strings separated by single quotes. The reason for using single quoted strings is to protect variable names from parsing, otherwise double quotes are required to escape variable names, for example, / $avar.Return value:This function returns a unique function name as a string, otherwise it returns FALSE on error.The following programs illustrate the create_function() function in PHP:Program 1:Create anonymous function using create_function()
// create a function from information
// collected at runtime,  $newfunc = create_function ( `$a, $b` , ` return
"ln ($a) + ln ($b) = " . log ( $a * $b ); `); echo " New anonymous function: $newfunc " ; echo $newfunc (2, M_E ). "" ; ?>
Exit:
New anonymous function : lambda_1 ln (2) + ln (2.718281828459) = 1.6931471805599 
Program 2:Create a generic function using create_function()
// General function that can apply a set
// operations with 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 (< / code> $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 create a bunch of inline 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 ); ?>
Exit:
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: engineerforengineer Similar Character: 13 
Links: http: / /php.net/manual/en/function.create-function.php



Get Solution for free from DataCamp guru