PHP Anonymous functions

PHPServer Side ProgrammingProgramming

Introduction

Anonymous function is a function without any user defined name. Such a function is also called closure or lambda function. Sometimes, you may want a function for one time use. Closure is an anonymous function which closes over the environment in which it is defined. You need to specify use keyword in it.Most common use of anonymous function to create an inline callback function.

Syntax

$var=function ($arg1, $arg2) { return $val; };
  • There is no function name between the function keyword and the opening parenthesis.
  • There is a semicolon after the function definition because anonymous function definitions are expressions
  • Function is assigned to a variable, and called later using the variable’s name.
  • When passed to another function that can then call it later, it is known as a callback.
  • Return it from within an outer function so that it can access the outer function’s variables. This is known as a closure.

Anonymous function example

Example

 Live Demo

<?php
$var = function ($x) {return pow($x,3);};
echo "cube of 3 = " . $var(3);
?>

Output

This will produce following result. −

cube of 3 = 27

Anonymous function as callback

In following example, an anonymous function is used as argument for a built-in usort() function. The usort() function sorts a given array using a comparison function

Example

 Live Demo

<?php
$arr = [10,3,70,21,54];
usort ($arr, function ($x , $y) {
   return $x > $y;
});
foreach ($arr as $x){
   echo $x . "\n";
}
?>

Output

This will produce following result. −

3
10
21
54
70

Anonymous function as closure

Closure is also an anonymous function that can access variables outside its scope with the help of use keyword

Example

 Live Demo

<?php
$maxmarks=300;
$percent=function ($marks) use ($maxmarks) {return $marks*100/$maxmarks;};
echo "marks=285 percentage=". $percent(285);
?>

Output

This will produce following result. −

marks=285 percentage=95
raja
Published on 18-Sep-2020 13:35:13
Advertisements