php
38 lines · 8 steps
How memoization works in PHP closures
A higher-order function caches any callable's results by its arguments using a closure that captures state by reference.
Explained by
highlit
1function memoize(callable $fn): callable
2{
3 $cache = [];
4
5 return function (...$args) use (&$cache, $fn) {
6 $key = md5(serialize($args));
7
8 if (array_key_exists($key, $cache)) {
9 return $cache[$key];
10 }
11
12 return $cache[$key] = $fn(...$args);
13 };
14}
15
16$fibonacci = memoize(function (int $n) use (&$fibonacci): int {
17 return $n < 2 ? $n : $fibonacci($n - 1) + $fibonacci($n - 2);
18});
19
20$primeFactors = memoize(function (int $number): array {
21 $factors = [];
22 $divisor = 2;
23
24 while ($number > 1) {
25 while ($number % $divisor === 0) {
26 $factors[] = $divisor;
27 $number = intdiv($number, $divisor);
28 }
29 $divisor++;
30
31 if ($divisor * $divisor > $number && $number > 1) {
32 $factors[] = $number;
33 break;
34 }
35 }
36
37 return $factors;
38});
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Capturing a variable by reference lets a closure keep mutable state alive across many calls.
- 2Serializing and hashing arguments gives a stable cache key for arbitrary input shapes.
- 3Recursive functions gain the biggest speedup from memoization because each subproblem is solved once.
Related explainers
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
php
<?php namespace App\Console\Commands;
Releasing stale document locks in Laravel
artisan-command
transactions
row-locking
Intermediate
6 steps
java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
Building a trie for autocomplete in Java
trie
prefix-tree
recursion
Intermediate
8 steps
php
<?php namespace App\Providers;
Subdomain multi-tenancy routing in Laravel
multi-tenancy
service-container
route-binding
Advanced
7 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-memoization-works-in-php-closures-explained-php-2dc8/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.