Search⌘ K

Arrow Functions

Explore the concept of arrow functions in PHP 8, their shorthand syntax compared to anonymous functions, and understand when to use them effectively. Learn variable inheritance in arrow functions and see practical examples, including creating a text-based CAPTCHA using arrow functions and PHP 8 features to enhance code readability and efficiency.

Arrow functions were actually first introduced in PHP 7.4. However, as many developers do not follow every single release update, it’s important to include coverage of this excellent new feature.

In this lesson, we will learn about arrow functions and their syntax, as well as the advantages and disadvantages compared with anonymous functions.

Generic syntax

Simply put, an arrow function is a shorthand syntax for the traditional anonymous function, much like the ternary operator is a shorthand syntax for if () {} else {}. The generic syntax for an arrow function is shown here:

fn(<ARGS>) => <EXPRESSION>

<ARGS> is optional and includes anything seen in any other user-defined PHP function. <EXPRESSION> can include ...