Arrow Functions in PHP. How to use them?

In PHP, we can create functions using arrow functions (also known as short closures).

Using arrow functions, we can define them in a single line, resulting in cleaner and easier-to-maintain code.

Arrow Function Syntax

The basic structure of an arrow function is as follows:

Difference compared to the traditional syntax

Previously, we’d write this:

Now we can use an arrow function:

Let’s elaborate on the syntax.

The fn keyword

Arrow functions use the fn keyword instead of the function keyword.

No need for return

In arrow functions, values are returned implicitly. There is no need for the return keyword.

No {} brackets are needed

Arrow functions can only have a single expression.

They cannot have multiple statements, blocks of code, loops, or conditionals that span multiple lines.

Thus, they have no need for brackets.

This one expression can be spread over multiple lines for better formatting, but it should be one expression.

No need for the Use keyword

Arrow functions automatically inherit data from their outer scope; the use keyword is unnecessary.

In a traditional anonymous function we explicitly use the use keyword.

Arrow functions automatically inherit the variable $multiplier residing out of the $multiplyArrow function, while traditional functions require the use keyword.

Arrow functions support the same features as anonymous functions

Multiple Parameters

Arrow functions can take multiple parameters.

Nested Functions

Arrow functions support nesting.

A normal function equivalent is:


Conditional logic

We can use conditional logic, as long as it is a single expression. Thus we cannot use if…else statements but it is perfectly alright to use ternary operators or null coalescing.

Example of ternary operator in arrow functions:

Example of null coalescing in arrow functions:

When to use them?

Arrow functions are particularly useful when working with array functions like array_map(), array_reduce(), etc.

Their single expression nature makes it easier to pass closures to these functions.

However, for complex logic, traditional closures with function remain the better choice.

Although my blog doesn’t support comments, feel free to reply via email or X.