Anonymous Functions and Closures
Write inline functions and capture variables with use.
What Are Anonymous Functions?
An anonymous function (lambda) is a function without a name. In PHP it's an instance of the built-in Closure class and can be stored in a variable, passed as an argument, or returned from another function.
Basic Anonymous Function
Assign a function to a variable and call it:
<?php
$double = function(int $n): int {
return $n * 2;
};
echo $double(5); // 10
echo $double(21); // 42All lessons in this course
- Defining and Calling Functions
- Default and Variadic Parameters
- Variable Scope: Local and Global
- Anonymous Functions and Closures