Skip to content

31: Caching Stateless Closures

Compare two closure factories. One creates a static closure without captured or persistent state. The other captures the requested increment.

  • PHP 8.6 CLI. Confirm the version with php --version.
  • Review the previous chapter if you’re following the series in order.

Allow about 10 minutes for the walkthrough and exercise.

A runnable stateless-closure-cache.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/31-stateless-closure-cache/stateless-closure-cache.php
stateless-closure-cache.php
<?php
declare(strict_types=1);
function incrementer(): Closure
{
return static fn (int $value): int => $value + 1;
}
function stepper(int $step): Closure
{
return static fn (int $value): int => $value + $step;
}
$first = incrementer();
$second = incrementer();
echo 'Stateless reused: ', $first === $second ? 'yes' : 'no', PHP_EOL;
echo 'Captured reused: ', stepper(2) === stepper(2) ? 'yes' : 'no', PHP_EOL;
echo 'Stepped value: ', stepper(3)(4), PHP_EOL;
Stateless reused: yes
Captured reused: no
Stepped value: 7

PHP 8.6 can cache a stateless closure at its declaration site. A closure that captures a variable needs its own state. Behavior should remain your public contract, especially when supporting different PHP releases.

Add a static local counter inside the first closure and check the identity result again. Each closure needs its own counter.

Continue with Benchmark JSON Encoding on Your Data.