Back to course

Anonymous Functions and Closures

PHP: The Complete 0 to Hero Bootcamp

20. Anonymous Functions and Closures

Modern PHP utilizes functions that do not have a defined name. These are crucial for concepts like callbacks, filtering arrays, and passing logic as arguments.

Anonymous Functions (Lambdas)

An anonymous function is a function without a name, stored in a variable.

php

Closures

An anonymous function becomes a closure when it imports variables from the surrounding scope (the parent scope) using the use keyword.

Note: Anonymous functions in PHP cannot automatically access local variables from the surrounding scope; they must be explicitly imported.

php

New Modifier Value: " . $modifier; // Output: 7 ?>

Closures are widely used in frameworks and functions like array_map or array_filter.