CodeBlanks Logo Icon CodeBlanks

Higher-order functions

PHP course · Expert · Lesson 12/54

Learn to write higher-order functions that return or accept functions.

What is a higher-order function?

A function can both take another function as a parameter and return a function. Such functions are called higher-order.

For example makeMultiplier(2) returns fn($n) => $n * 2. You assign the returned closure to a variable and call it later. This produces flexible tools instead of fixed code.

This pattern is already used in built-ins like array_map and array_filter; now you write your own.

Function composition

The power of higher-order functions comes from composition. The output of one function can be the input of another.

For example compose($f, $g) returns fn($x) => $f($g($x)). This applies two operations in a single step.

This pattern is the heart of functional programming; you pipe data from one operation to the next. You build complex flows from small pieces.

Exercise The makeMultiplier function

Define a function makeMultiplier(float $factor) that returns an arrow function multiplying by the given factor (fn($n) => $n * $factor). Then call $triple = makeMultiplier(3); and print the result with echo $triple(5) . "\n";.

Show example solution
Write function makeMultiplier(float $factor) { return fn($n) => $n * $factor; }. Then $triple = makeMultiplier(3); and echo $triple(5) . "\n";.
Example solution:
<?php
// Write makeMultiplier and call it via $triple
function makeMultiplier(float $factor) {
    return fn($n) => $n * $factor;
}
$triple = makeMultiplier(3);
echo $triple(5) . "\n";

Test yourself

  1. What is a higher-order function?

    • A function that adds two numbers
    • A function that takes or returns a function
    • A function that only prints text
    • A method inside a class
    Show answer

    A function that takes or returns a function — Correct. A higher-order function takes a function as a parameter or returns one.

  2. Match the higher-order patterns

    makeMultiplier(2)
    Returns a closure
    array_map(...)
    Accepts a closure
    callable parameter
    Accepts a function
  3. A function that returns a function

    <?php
    function makeMultiplier($factor) {
        return ____ ($n) => $n * $factor;
    }
    $double = makeMultiplier(2);
    echo $double(5) . "\n";
    
    Show answer
    <?php
    function makeMultiplier($factor) {
        return fn ($n) => $n * $factor;
    }
    $double = makeMultiplier(2);
    echo $double(5) . "\n";
    

All lessons in Expert