⊗ppSpFnArF 8 of 95 menu

Arrow Functions in PHP

In this lesson, we will begin to study arrow functions. They represent a shortened version of anonymous functions. Their syntax looks like the following:

<?php fn (parameters) => expression; ?>

Let's rewrite a regular function as an arrow function. Suppose we have a function for adding two numbers:

<?php $func = function($num1, $num2) { return $num1 + $num2; }; echo $func(1, 2); ?>

Now let's make it an arrow function:

<?php $func = fn($num1, $num2) => $num1 + $num2; echo $func(1, 2); ?>

Rewrite the following function into an arrow function:

<?php $greet = function($name) { return 'hello ' . $name; }; echo $greet('fred'); ?>
byenru