Callbacks and Higher-Order Functions

8.Callbacks and Higher-Order Functions

M

In this chapter

We'll learn what higher-order functions are — functions that take other functions or return them — why passing formatPrice() instead of formatPrice(...) breaks a callback, how a function can build and return new functions, and how a list of small rule functions becomes a price pipeline, with array_reduce() or PHP 8.5's pipe operator.

14–16 min

The Problem in Real Life

Olivia wants the price rules to be a list she can reorder: base price, then add-ons, then the holiday surcharge, then any staff discount. "When the accountant says the discount must come before the surcharge, I want to move one line, not ask you to rewrite the function."

Mia starts with the day view's price column and writes array_map(formatPrice(), $prices). PHP stops with an ArgumentCountError: "Too few arguments to function formatPrice(), 0 passed".

M

I didn't call formatPrice — array_map was supposed to. Why is it complaining?

Mia

Calling a Function vs. Handing It Over

Calling vs. passing

formatPrice() runs the function now. formatPrice(...) hands the function over, to be run later.

Functions that build functions

A 10% rule and a 20% rule differ by one number. One function can make both.

Rules as a list

If each price step is a function, the whole calculation is a list of steps applied in order — easy to reorder.

Callbacks and Higher-Order Functions

Functions about functions: a higher-order function is one that takes a function as an argument, or returns one. You've used them since Act 08: array_map(), array_filter() and usort() all take a callback. This chapter writes your own:

  • Passing a function, not its result: the difference between f() and f(...).
  • Taking a function: your own functions with callable parameters.
  • Returning a function: factories that build closures.
  • Pipelines: a list of functions applied in order — with array_reduce() or the pipe operator |>.

Passing a function, not its result: formatPrice() with brackets calls the function right now, and whatever it returns is what gets passed on. In array_map(formatPrice(), $prices), PHP tries to call formatPrice() with no arguments before array_map() even starts — hence "Too few arguments". To hand over the function itself, use formatPrice(...) (chapter 7), an arrow function fn($p) => formatPrice($p), or the string "formatPrice". The rule: no brackets of your own when the other function will do the calling.

Mia's bug: calling instead of passing
<?php
declare(strict_types=1);
function formatPrice(int $pence): string
{
return "£" . number_format($pence / 100, 2);
}
$prices = [2500, 3025];
try {
array_map(formatPrice(), $prices); // calls formatPrice() right now, with nothing
} catch (ArgumentCountError $e) {
echo $e->getMessage(), "\n";
}
echo implode(" ", array_map(formatPrice(...), $prices)), "\n"; // pass the function
echo implode(" ", array_map(fn($p) => formatPrice($p), $prices)), "\n"; // or wrap it
// Too few arguments to function formatPrice(), 0 passed in main.php on line 13 and exactly 1 expected
// £25.00 £30.25
// £25.00 £30.25

Taking a function: any function can accept a function: give the parameter the type callable (or Closure) and call it like a function. function applyAll(int $pence, callable ...$rules): int takes any number of rules and runs them one after another. The caller decides what happens; your function decides when. That's the idea behind every callback: usort() knows how to sort, and you tell it how to compare.

Your own function that takes functions
<?php
declare(strict_types=1);
function applyAll(int $pence, callable ...$rules): int
{
foreach ($rules as $rule) {
$pence = $rule($pence);
}
return $pence;
}
$withTowel = fn(int $p): int => $p + 250;
$staffDiscount = fn(int $p): int => $p - intdiv($p * 20, 100);
echo applyAll(2500, $withTowel), "\n"; // 2750
echo applyAll(2500, $withTowel, $staffDiscount), "\n"; // 2200

Returning a function: a function can build and return a closure. function surcharge(int $percent): Closure { return fn(int $p): int => $p + intdiv($p * $percent, 100); } makes a rule for any rate: surcharge(10) is the bank-holiday rule, surcharge(20) the Christmas Eve rule. Each returned closure remembers the $percent it was made with (chapter 6). A function that builds other functions is often called a factory.

A factory: a function that returns functions
<?php
declare(strict_types=1);
function surcharge(int $percent): Closure
{
return fn(int $p): int => $p + intdiv($p * $percent, 100);
}
$bankHoliday = surcharge(10);
$christmasEve = surcharge(20);
echo $bankHoliday(2750), " ", $christmasEve(2750), "\n"; // 3025 3300
echo surcharge(15)(2750), "\n"; // 3162: build and call at once

A pipeline of rules: put the steps in an array, in order, and apply them one after another: start with the base price, give it to the first rule, give that result to the next rule, and so on. That's exactly array_reduce() from Act 08: array_reduce($rules, fn($pence, $rule) => $rule($pence), $base). Reordering the rules is now reordering an array — Olivia's "move one line". The diagram below shows a price passing through the pipeline.

Daniel's booking through the price pipeline

2500

base price: a haircut

rule 1

withAddOns

+ 250 for the hot towel → 2750

rule 2

surcharge(10)

+ 10% for the bank holiday → 3025

show

formatPrice(...)

"£30.25" — on every screen

A pipeline of rules with array_reduce()
<?php
declare(strict_types=1);
function surcharge(int $percent): Closure
{
return fn(int $p): int => $p + intdiv($p * $percent, 100);
}
$rules = [
"add-ons" => fn(int $p): int => $p + 250,
"holiday" => surcharge(10),
];
$price = array_reduce($rules, fn(int $p, callable $rule): int => $rule($p), 2500);
echo $price, "\n"; // 3025
$rules = ["staff" => fn(int $p): int => $p - 500] + $rules; // a new first step
echo array_reduce($rules, fn(int $p, callable $rule): int => $rule($p), 2500), "\n"; // 2475

The pipe operator: PHP 8.5 added the pipe operator |>, which you met in Act 05: $base |> withTowel(...) |> surcharge(10) passes the value on the left into the function on the right, step by step, and reads in the order things happen. Each step must be a function that takes exactly one argument. An arrow function in a pipe needs brackets around it: |> (fn($p) => $p - 500). Use |> when the steps are fixed in the code, and an array of rules when they need to change at runtime. The table below sums up the patterns.

Table — Higher-order patterns
PatternExampleUse it for
Pass a functionarray_map(formatPrice(...), $prices)Letting another function call yours
Take a functionfunction applyAll(int $p, callable ...$rules)Letting the caller decide what happens
Return a functionfunction surcharge(int $percent): ClosureBuilding similar rules from settings
Pipeline with an arrayarray_reduce($rules, fn($p, $r) => $r($p), $base)Steps that change at runtime
Pipe operator (PHP 8.5)$base |> withTowel(...) |> surcharge(10)Fixed steps, read in order
The pipe operator |> (PHP 8.5)
<?php
declare(strict_types=1);
function withTowel(int $p): int
{
return $p + 250;
}
function surcharge(int $percent): Closure
{
return fn(int $p): int => $p + intdiv($p * $percent, 100);
}
echo 2500 |> withTowel(...) |> surcharge(10), "\n"; // 3025
echo 2500 |> (fn($p) => $p - 500) |> surcharge(10), "\n"; // 2200: brackets around fn

Key Takeaway

A higher-order function takes or returns a function. Pass the function itself — formatPrice(...) or fn($p) => ... — never formatPrice(), which calls it on the spot. Parameters typed callable take rules from the caller; factories return closures that remember their settings; and a list of one-argument rules applied with array_reduce() (or chained with |> in PHP 8.5) becomes a pipeline you can reorder.

Why This Matters

Business rules change: a new surcharge, a discount that must come first, a rule only for one day. When each rule is a small function and the calculation is a list of them, a change is one line in one place — and each rule can be tested on its own.

Higher-order functions are also how frameworks are built. Laravel's middleware, event listeners, collection methods and validation rules are all "give me a function, I'll call it at the right moment".

The price is now a pipeline, and Olivia reorders rules by moving a line. The receipt page needs both the checkout helpers and the invoice helpers — and the moment Mia includes both files, the page dies: "Cannot redeclare function formatPrice()". Both files had their own copy. That's the next chapter: built-in functions, and how PHP keeps track of function names.