Topics Control Flow & Functions Closures & Arrow Functions
intermediate 12 min read

Closures & Arrow Functions

Anonymous functions, closures, and PHP 7.4+ arrow functions.

Anonymous Functions (Closures)

\$greet = function(string \$name): string {
return "Hello \$name";
};
echo \$greet("Alice");

// Inherit variables with use
\$prefix = "Mr.";
\$greet = function(\$name) use (\$prefix): string {
return "Hello \$prefix \$name";
};

Arrow Functions (PHP 7.4+)

\$numbers = [1, 2, 3, 4];
\$doubled = array_map(
fn(\$n) => \$n * 2,
\$numbers
);

// Arrow functions automatically inherit parent scope

Callable Type

function process(array \$items, callable \$callback): array {
return array_map(\$callback, \$items);
}

Examples

<?php
$nums = [1,2,3,4,5];
$squared = array_map(fn($n) => $n ** 2, $nums);
print_r($squared);

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.