Skip to main content

Lesson 2 of 8

Anonymous Functions, Closures & Arrow Functions

Anonymous functions (closures) are functions without a name - assigned to variables or passed as arguments. They are the foundation of PHP's functional programming style and are used extensively in array functions (array_map, usort) and callbacks. Arrow functions (PHP 7.4+) are a concise syntax that automatically inherit outer scope variables.

14 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Closures, Binding & Arrow Functions

Closures, Binding & Arrow Functions
<?php
declare(strict_types=1);

// ── Anonymous function ────────────────────────────────────────
$greet = function(string $name): string {
    return "Hello, $name!";
};
echo $greet("Bob");     // Hello, Bob!

// ── Closure - captures outer scope with 'use' ─────────────────
$prefix = "Dr.";
$formatName = function(string $name) use ($prefix): string {
    return "$prefix $name";
};
echo $formatName("Smith");   // Dr. Smith

// Capture by REFERENCE (variable value at call time, not definition)
$count = 0;
$increment = function() use (&$count): void {
    $count++;
};
$increment(); $increment(); $increment();
echo $count;    // 3  (would be 0 without &)

// ── Arrow function (PHP 7.4+) - automatically captures outer scope ──
// Clean, concise, no 'use' needed - best for single-expression functions
$multiplier = 3;
$multiply = fn(int $n): int => $n * $multiplier;   // $multiplier auto-captured
echo $multiply(5);     // 15

// Arrow functions are always one expression - use closures for multi-line

// ── Using closures as callbacks ────────────────────────────────
$posts = [
    ["id" => 1, "title" => "PHP Basics",   "views" => 500],
    ["id" => 2, "title" => "PDO Guide",    "views" => 1200],
    ["id" => 3, "title" => "PHP Security", "views" => 800],
];

// array_map with arrow function
$titles = array_map(fn($post) => $post["title"], $posts);
// ["PHP Basics", "PDO Guide", "PHP Security"]

// array_filter with closure
$popular = array_filter($posts, fn($post) => $post["views"] > 700);

// usort with arrow function
usort($posts, fn($a, $b) => $b["views"] <=> $a["views"]);  // descending

// ── Closures as strategies (pattern) ───────────────────────────
function applyToPost(array $post, callable $transform): array {
    return $transform($post);
}

$addExcerpt = function(array $post): array {
    $post["excerpt"] = mb_substr($post["title"], 0, 20) . "...";
    return $post;
};

$result = applyToPost($posts[0], $addExcerpt);
$result = applyToPost($posts[0], fn($p) => array_merge($p, ["featured" => true]));

Quick Quiz

Tip

Tip

Practice Anonymous Functions Closures Arrow Functions in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Anonymous Functions, Closures & Arrow Functions

Practice Task

Note

Practice Task - (1) Write a working example of Anonymous Functions Closures Arrow Functions from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Anonymous Functions Closures Arrow Functions is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done