Arrow FunctionsArrow functions were introduced in PHP 7.4 as a more concise syntax for anonymous functions. Both anonymous functions and arrow functions are implemented using the Closure class.
Arrow functions have the basic form
Arrow functions support the same features as anonymous functions, except that using variables from the parent scope is always automatic. When a variable used in the expression is defined in the parent scope it will be implicitly captured by-value. In the following example, the functions $fn1 and $fn2 behave the same way.
Example #1 Arrow functions capture variables by value automatically
The above example will output: 4 This also works if the arrow functions are nested:
Example #2 Arrow functions capture variables by value automatically, even when nested
Similarly to anonymous functions, the arrow function syntax allows arbitrary function signatures, including parameter and return types, default values, variadics, as well as by-reference passing and returning. All of the following are valid examples of arrow functions:
Example #3 Examples of arrow functions
Arrow functions use by-value variable binding.
This is roughly equivalent to performing a
Example #4 Values from the outer scope cannot be modified by arrow functions
Changelog
Notes
|