Sunday, November 17, 2024
Google search engine
HomeLanguagesPHP create_function() Function

PHP create_function() Function

The create_function() is an inbuilt function in PHP which is used to create an anonymous (lambda-style) function in the PHP.

Syntax:

string create_function ( $args, $code )

Parameters: This function accepts two parameters which is describes below:

  • $args: It is a string type function argument.
  • $code: It is a string type function code.

Note: Usually, these parameters will be passed as single quote delimited strings. The reason for using single quoted strings is to protect the variable names from parsing, otherwise, double quotes will be needed to escape the variable names, e.g. \$avar.

Return Value: This function returns a unique function name as a string, Otherwise returns FALSE on error.

Below programs illustrate the create_function() function in PHP:

Program 1: Creating an anonymous function with 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\n";
echo $newfunc(2, M_E) . "\n";
?>


Output:

New anonymous function: lambda_1
ln(2) + ln(2.718281828459) = 1.6931471805599

Program 2: Create a general function with 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) . "\n";
    }
}
  
// 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"
        "\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);
?>


Output:

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 : neveropen
Similar Character : 13

Reference: http://php.net/manual/en/function.create-function.php

RELATED ARTICLES

Most Popular

Recent Comments