PHP Higher Order Functions

A higher-order function or, a first-class functions, is defined as one that can accept other functions as arguments or return another function. Both are intimately related, as the ability of a language artifact to be passed in as an argument or returned from a functions hinges on it being considered just another object. This also means, of course, that functions can be assigned to variables.

Assigning a function to a variable

$concat2 = function (string $s1, string $s2): string {
    return $s1. ' '. $s2;
};
$concat2('Hello', 'World');  //-> 'Hello World'

This code takes the anonymous function and assigns it to the variable $concat2. Alternatively, you can check for the presence of a function variable using is_callable():

is_callable($concat2) // true

Returned from a function

Functions can also be returned from other functions, ‘notice the : callable type hint. This is an extremely useful technique for creating families of functions. It’s also the main part of implementing argument currying

function concatWith(string $a): callable {
   return function (string $b) use ($a): string {
      return $a . $b;	
   };
}

$helloWith = concatWith('Hello');
$helloWith('World'); //-> 'Hello World'

A callable as a parameter

A php function argument can be a callable variable

// Use case 1
function apply(callable $func, $a, $b) {
   return $func($a, $b);
}

$add = function (float $a, float $b): float {
   return $a + $b;
};

$divide = function (float $a, float $b): float {
   return $a / $b;
};

apply($add, 5, 5); //-> 10
apply($divide, 5, 5); //-> 10	

// Use case 2

function apply(callable $func): callable {
   return function($a, $b) use ($func) {
      return $func($a, $b);
   };
}