PHP Tutorial: How to Use "create_function" to Create New and Anonymous Functions in PHP
This PHP tutorial will help you in learning some basics of "create_function()" function of PHP, which allows programmers to create function on the go. This function allows us to create new and anonymous functions in the form of PHP statements without being diverted from program flow to define it. Its need arises mostly in cases where we have to handle some smaller tasks such as mathematical calculations that can done in single line of PHP code.
Important Details about PHP create_function()
In this section, I'm publishing some important details about PHP "create_function()" function which need to be known at basic level before using this function. First of all, below is the syntax of this function. To learn more about PHP function syntax's, then, you can read my article on it.
Syntax of PHP "create_function" Function
string create_function ( string $args , string $code );
Description About Function Arguments Or Parameters
First of all, You need to note down one thing that you should pass parameters as single quote delimited strings to avoid variable names from being parsed OR you can escape escape the variable names using backslash character inside double quotes.
- "$args" - Here, you can specify the function arguments, which are going to be needed in our new function. You can specify as many variables inside this while seperating them with comma (",") symbol.
- "$code" - Here, you need to submit code of new function, which will going to be executed.
Return a unique function name such as "lambda_1" as string or Boolean "false" on error.
Examples Showing Usage of PHP "create_function()" function
Here, below is the code snippet showing the usage of this function in various ways.
<?php //Here, below is the simple usage of this function $newfunc = create_function('$val_1,$val_2', 'return $val_1 + $val_2;'); echo "New anonymous function: $newfunc\n"; echo $newfunc(2, M_E) . "\n"; // Above code will output /** ***New anonymous function: lambda_1 ***6 ***/ //Here is the example of Using anonymous functions // as callback functions $av = array("I'm ", "in ", "Luv ", "With "); array_walk($av, create_function('&$v,$k', '$v = $v . "Geeta";')); print_r($av); /** ***Above Code will output Array (  => I'm Geeta  => in Geeta  => Luv Geeta  => With Geeta ) *** ***/ ?>
So, that's all which you need to know (Basic Knowledge) about this function before using it. Hope, It may serve any kind of help to you.