PHP Anonymous Function

In this chapter you will learn:

  1. What is PHP Anonymous Functions
  2. Why do we need Anonymous Functions
  3. Syntax to create anonymous functions
  4. 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:

  1. What is PHP static variable
  2. Syntax to declare PHP static variable
  3. Note for static variable
  4. Example - static variable
Home » PHP Tutorial » PHP Function Create
PHP Function
PHP Function Create
PHP Function Parameter
PHP Function Default Parameters
PHP Variable Length Parameter
PHP Function Reference Parameter
PHP Function Return
PHP Return Reference
PHP Variable Scope in Functions
PHP Global Variables
PHP Recursive Functions
PHP Anonymous Function
PHP static variable