PHP Anonymous Function
In this chapter you will learn:
- What is PHP Anonymous Functions
- Why do we need Anonymous Functions
- Syntax to create anonymous functions
- Example - creates an anonymous function dynamically based on the value of a variable
Description
PHP anonymous functions have no name.
Why
You might want to create anonymous functions for two reasons:
- To create functions dynamically
- To create short-term, disposable functions
Syntax
To create an anonymous function, you use separated list of parameters if any, and the code for the function body.
$myFunction = create_function( '$param1, $param2', 'function code here;' );
Example
Here's an example that creates an anonymous function dynamically based on the value of a variable:
<?PHP// j a v a 2s.com
$mode = "+";
$processNumbers = create_function( '$a, $b', "return \$a $mode \$b;" );
echo $processNumbers( 2, 3 ); // Displays "5"
?>
The code above generates the following result.
This code uses the value of the $mode variable as the operator used to process its two arguments, $a and $b. For example, if you change $mode to "*", the code displays "6".
Next chapter...
What you will learn in the next chapter:
- What is PHP static variable
- Syntax to declare PHP static variable
- Note for static variable
- Example - static variable
Home » PHP Tutorial » PHP Function Create