Categories
PHP

Arrow and Anonymous Functions

In this tutorial we’ll use and compare anonymous and arrow functions.

  1. Anonymous functions
  2. Arrow functions

Anonymous function

You can use anonymous functions in PHP since version 5.4. They are called anonymous functions because, unlike regular functions, they don’t have a function name. You can define an anonymous function the way you define a named function, the only difference is that you don’t assign a name to the function.:

<?php
 # named traditional/regular function
 function double($a){
  return $a * 2;
 }

 # anonymous function
 $var = function($a) {
         return $a * 2;
        };
 echo double(2); # 4
 echo $var(3);   # 6 

An anonymous function can assign to a variable and then you can use the variable name to execute the anonymous function or it can pass as a parameter of another function.

<?php
 $array = [
  ['username' => 'BrainBell', 'email' => 'info@brainbell.com'],
  ['username' => 'ADMIN', 'email' => 'admin@brainbell.com'],
  ['username' => 'Team', 'email' => 'brainbellteam@outlook.com']
 ];


 $usernames = array_map(
  function ($array) {
   return $array['username'];
  }, 
  $array
 );

print_r($usernames);
# Array ( [0] => BrainBell [1] => ADMIN [2] => Team )

Arrow function

Arrow functions were introduced in PHP 7.4. They are the shorthand form of the anonymous function. Like anonymous functions, the arrow function supports the same features.

<?php
 # Anonymous function
 $anon = function($a) {
          return $a * 2;
         };
 echo $anon(5); # 10

The anonymous function in the above code can be rewritten as an arrow function like this:

<?php
 # Arrow function
 $arrow = fn($a) => $a * 2;
 echo $arrow(5); # 10

The function keyword is shortened to fn, no curly braces are needed, and the return keyword is not required.

As described in the PHP documentation: Arrow functions support the same features as anonymous functions, except that using variables from the parent scope is always automatic.

https://php.net/manual/functions.arrow.php

Arrow functions can access variables from the parent scope but anonymous can not, see the following example:

<?php
 $m = 2;
 $arrow = fn ($a) => $a * $m;
 echo $arrow(5); # 10

Anonymous functions can access variables from the parent scope by using the use keyword:

<?php
 $m = 2;
 $anon = function($a) use ($m) {
           return $a * $m;
          };
 echo $anon(5); # 10

For more information, read the Closures in PHP tutorial.

Nesting arrow functions:

<?php
 $m = 2;
 $arrow = fn($a) => fn($b) => $a * $b * $m;
 echo $arrow(5)(3); # 30

When to use anonymous and arrow functions

Anything that requires a temporary function that you probably will only use once. I would use them for callbacks, for functions such as preg_replace_callback and usort:

Example: Using anonymous function with preg_replace_callback function

<?php
 # Anonymous function example
 $text = "<p>some text</p>";
 $rtxt = preg_replace_callback(
         '|<p>(.*?)</p>|',
         function ($m) {
          return strtoupper($m[1]);
         },
         $text);
 echo $rtxt; # Prints: SOME TEXT

Example: Using arrow function with preg_replace_callback function

<?php
 # Arrow function example
 $text = "<p>some text</p>";
 $rtxt = preg_replace_callback(
          '|<p>(.*?)</p>|',
          fn ($m) => strtoupper($m[1]),
          $text);
 echo $rtxt; # Prints: SOME TEXT

Example: Using anonymous function with usort

<?php
 # Anonymous function example
 $arr = ['100',3,7,1];
 usort ($arr, function ($x , $y) {
  return $x > $y;
 });
 print_r($arr);
 /* Prints: Array(
    [0] => 1
    [1] => 3
    [2] => 7
    [3] => 100)*/

Example: Using arrow function with usort

<?php
 # Arrow function example
 $arr = ['100',3,7,1];
 usort ($arr, fn ($x , $y) =>  $x > $y);
 print_r($arr);
 /* Prints: Array(
    [0] => 1
    [1] => 3
    [2] => 7
    [3] => 100) */

User-defined functions:

  1. Defining functions
  2. Passing variables by reference
  3. Using arrow and anonymous functions
  4. Understanding variable scope
  5. Including external files