Saturday, September 2, 2017

PHP Anonymous functions


Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses.

Closures can also be used as the values of variables

Lets see the below examples for clear understanding.

Example - 1 :
<?php
// php anonymous functions

$java = function(){
    return 10;
};
echo $java() ;

?>
Output:
-----------------------
10

Example - 2 :
<?php
// php anonymous functions with parameter

$add = function($a,$b){
    return $a+$b;
};
echo $add(10,20) ;

?>
Output:
------------------
30

Example - 3 :
<?php
// php anonymous functions

$add = function($a,$b){
    return $a+$b;
};

// assigning the result to anoher variable
$result = $add;
echo $result(10,20) ;

?>
Output:
---------------------
30


No comments:

Post a Comment