Lab 06: Functional PHP — Closures & Pipelines

Objective

Master PHP's functional programming toolkit: first-class functions, closures with use, higher-order functions (array_map, array_filter, array_reduce), currying, function composition, lazy evaluation with generators, and building a data transformation pipeline.

Background

PHP is a multi-paradigm language — you can write it functionally without any framework. Functional style produces more testable code because pure functions (same input → same output, no side effects) are easy to unit test. PHP closures capture variables by value by default; the use (&$var) syntax captures by reference. First-class callable syntax (strlen(...)) was added in PHP 8.1 and eliminates Closure::fromCallable() boilerplate.

Time

30 minutes

Prerequisites

  • PHP Foundations Lab 05 (Functions & Closures)

Tools

  • Docker: zchencow/innozverse-php:latest


Lab Instructions

Step 1: Closures, use, and first-class callables

💡 Arrow functions (fn()) capture by value automatically. Unlike regular closures which require explicit use ($var), arrow functions automatically capture all variables in scope by value. They are single-expression — no {} block, no return keyword. Use arrow functions for short, pure transformations; use closures for multi-line logic or when you need use (&$ref) by-reference capture.


Step 2: Higher-order functions + pipeline

📸 Verified Output:


Summary

Function
Signature
Use for

array_map

fn($item)

Transform every element

array_filter

fn($item): bool

Keep matching elements

array_reduce

fn($carry, $item)

Fold to single value

usort

fn($a, $b): int

Sort with custom comparator

pipe()

pipe($val, [$fn,...])

Sequential transformations

Currying

$fn = curry($multi)

Partial application

Further Reading

Last updated