PHP / CHAPTER 07

Closures and capture policies

Advanced

Make the difference between captured values and references explicit.

By the end of this chapter

  • Use explicit use captures
  • Trace by-value versus by-reference capture
  • Recognize arrow-function capture behavior

The idea

A PHP closure can import surrounding variables with use. A by-value capture records the variable’s value when the closure is created, while use (&$name) refers to the surrounding variable container and observes later changes. Arrow functions automatically capture used outer variables by value. Capture policy is therefore part of the behavior, not merely a syntactic preference.

By-value capture does not imply a deep copy of referenced objects. If the captured value is an object identifier, property mutation can still affect the shared object. A stateful closure can be useful for accumulating work, but a supposedly repeatable transformation should not depend on hidden changing state. Keep data ownership and lifetime visible when callbacks are stored and executed much later than their creation.

PHP example
<?php
$n=2;
$value=function()use($n){return $n;};
$reference=function()use(&$n){return $n;};
$n=5;echo $value(),":",$reference(),"\n";
Result
2:5

The value capture retains two, while the reference capture reads the current surrounding variable value five.

Try it yourself

Build a closure that accumulates amounts in private retained state and compare two independently created accumulators.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What does fn() => $n retain when $n is an integer?