PHP Anonymous Function

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//from w  ww .  j a  v a 2s  .co  m
        $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".





















Home »
  PHP Tutorial »
    Language Basic »




PHP Introduction
PHP Operators
PHP Statements
Variable
PHP Function Create
Exception
PHP Class Definition