User Tools

Site Tools


essentials:short_closure_functions

12. Short Closures (fn) — Small Functions With Clear Intent

Short closures give us a concise way to express small,
single‑expression functions. They reduce ceremony and make intent visible
without the weight of full closure syntax.

They reflect a broader shift in modern PHP:
small pieces of behavior should be easy to express and easy to read.


1. What Short Closures Are

A short closure is a compact function
that returns the value of a single expression:

$double = fn(int $x) => $x * 2;

No function keyword.
No use clause.
No braces.

Just the behavior.


2. Why Modern PHP Uses Them

Short closures reduce:

  • boilerplate
  • visual noise
  • unnecessary ceremony
  • the distance between intention and expression

They make small functions feel natural and readable.


3. The Mental Model

A short closure is a tiny piece of behavior.

It’s not a replacement for full closures.
It’s not for complex logic.
It’s not for branching or side effects.

The key idea:
Use short closures when the function expresses a single, clear expression.

If it needs more than that,
use a full closure.


4. A Simple Example

Without short closures:

$names = array_map(function ($user) {
    return $user->name;
}, $users);

With short closures:

$names = array_map(fn($user) => $user->name, $users);

Same meaning.
Less noise.
More clarity.


5. When to Use Short Closures

Use them when:

  • the function is a single expression
  • the behavior is small and clear
  • we’re mapping, filtering, or transforming
  • we want readability and flow
  • we want to avoid ceremony

Short closures shine in pipelines,
array functions, and small behavioral helpers.


6. When Not to Use Short Closures

Avoid them when:

  • the logic spans multiple steps
  • we need branching or loops
  • the behavior has side effects
  • clarity suffers from compression
  • the function deserves a name

Short closures are for small expressions,
not small programs.


When AI Gets This Wrong

AI often overuses short closures, squeezing multi‑step logic into a single expression.
Sometimes it nests short closures inside each other, or uses them where a named method would be clearer.

Our mental model helps us see when a short closure expresses real clarity — and when AI is using it simply because it “looks concise”.


Summary

Short closures let us express small pieces of behavior with clarity and minimal ceremony.
They reduce noise, improve readability, and help the code flow naturally.

Once we internalize this, we can immediately see when AI‑generated code:

  • compresses too much into a short closure
  • nests closures unnecessarily
  • uses short closures where a named method is clearer
  • or misses opportunities to simplify small behaviors

Short closures are a small feature
— but they teach us
how modern PHP wants to express behavior with elegance and intention.


essentials/short_closure_functions.txt · Last modified: by editor