• PHP Video Tutorials

PHP - create_function()



The create_function() function is an inbuilt function that can be used to create an anonymous (lambda-style) function.

Syntax

string create_function( string $args , string $code )

The create_function() function can create an anonymous function from the passed parameters and return a unique name. Usually, args are passed as a string in apostrophes that are also recommended for the code parameter. The reason for using apostrophe strings is to protect variable names from processing. In other words, if we use quotes, we need to escape all variable names like this: \ $ avar.

The create_function() function can return a unique function name as a string, or false on error.

Example 1

<?php
   $triangle = create_function('$b, $h', 'return "triangle = " . ($b*$h)/2;');
   echo $triangle(4,6);
?>

Output

triangle = 12

Example 2

<?php
   $str = "hello world!";
   $lambda = create_function('$match', 'return "friend!";');
   $str = preg_replace_callback('/world/', $lambda, $str);
   
   echo $str ;
?>

Output

hello friend!!
php_function_reference.htm
Advertisements