Arrow function in PHP 7.4



Arrow functions, introduced in PHP 7.4, provides a concise way to write functions in PHP 7.4. Short closures, also called Arrow functions, are a way of writing shorter functions in PHP 7.4.

This notation is useful when passing closures to functions like array_map or array_filter.

Arrow functions can be used

  1. Available as of PHP 7.4
  2. No return keyword allowed
  3. Have one expression, which is the return statement
  4. Start with the fn keyword

Here are some examples, so you can differentiate Arrow function:

1) array_map function

Current
$ids = array_map(function ($post) {
       return $post->id;
}, $posts);

Using Arrow function
// A collection of post objects

$posts = [/*...*/];
$ids = array_map(fn ($post) => $post->id, $posts);

2) map function


Current
$users->map(function ($user) {
       return $user->first_name.''.$user->last_name;
});

Using Arrow function
$users->map(fn ($user) => $user->first_name.''.$user->last_name);

I hope it can help you. You may like: OWASP Top 10 (Open Web Application Security Project)

Thank you.

Post a Comment

0 Comments