Using arrow functions
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 book.
In this section, you will learn about arrow functions and their syntax, as well as 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 include anything seen in any other user-defined PHP function. <EXPRESSION>
can include any standard PHP expression such as function calls, arithmetic operations, and so forth.
Let's now have a look at the differences between arrow functions and anonymous functions.