callbackfn

Anonymous function in PHP

Anonymous function means you can create a function without declaring its name and you can write a piece of code into it’s definition.

When you create a regular function you declare a name like sumNum etc. In later stage if you want to re-declare the same function name, it will not allowed you to declare same function name again. The code below is not allowed.

function sum($a, $b)
{
    return $a + $b;
}
function sum($a, $b, $c)
{
    return $a + $b + $c;
}

So sometimes you need a piece of code to reuse but you don’t want to assign a fixed name to that function at that time you can use Anonymous function.

Also one reason to create Anonymous function is, we can pass that function as argument to any other function.

Anonymous function is stored in a variable and variable value we can change any time. Notice that we have ; at end of function expression. Usually it is not in normal function expression.

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

echo $sum(3, 5);

Check how we can pass a function as variable as a callback function.

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

function mul($x, $y, $callback)
{
    $z = $x * $y;
    return $callback($z, 2);
}
echo mul(3, 5, $sum);

In short, callback function must be Anonymous function.

Now let’s see arrow function. arrow function is shorter way to define anonymous function. To make function with single expression easy, Arrow functions introduced. It removed 1) brackets {}, 2) return statement and 3)function keyword. If your function have more line of code logic then arrow functions are not for you. It must having a single line expression.

$gosum = fn($a, $b) => $a + $b;
echo $gosum(32, 5);