PHP - Using Anonymous Functions

Introduction

PHP can create anonymous functions.

To create an anonymous function, you use create_function().

This function takes two arguments:

  • a comma separated list of parameters if any, and
  • the code for the function body, minus the curly brackets, but including a semicolon at the end of each line of code.

It returns a unique, randomly generated string value that you can use to refer to the function later:

$myFunction = create_function('$param1, $param2','function code here;');

Demo

<?php

$processNumbers = create_function('$a, $b',"return \$a + \$b;");
echo $processNumbers(2, 3); // Displays"5"
?>// ww  w  .j  av  a2 s  .  c o  m

Result

Related Topic