PHP introduced the arrow function syntax in version 7.4. It’s just a shorthand way to write anonymous functions, sort of. The main difference between anonymous functions and arrow functions in PHP is the use of the _use _keyword. In order to have access to the scope outside of the anonymous function, you must use the _use _keyword. Arrow functions automatically have access to scope outside of the function.
Anatomy of an arrow function.
<?php
$global_var = 5;
$arrow_func = fn( $param ) => $param + $global_var;
echo $arrow_func( 5 );
?>
view raw
41 Arrow Function 2.php hosted with ❤ by GitHub
The arrow function starts with the shortened function keyword fn(); parameters can be declared inside of the parentheses. The arrow (=>) comes immediately after the _fn(), _which signifies that whatever comes next will be returned. You cannot enter an expression like the _echo _statement here since the arrow function implicitly uses the _return _statement. The arrow function also has access to the global variable $global_var. We don’t have to implement the _use _keyword like we’ve done so far with anonymous functions. We could have used an anonymous function with the aid of the _use _keyword to accomplish the same task.
#software-development #web-development #computer-science #php #programming #function