Development Blog
Collection of development articles I've put together...
Lambda Functions
A lambda function is an anonymous PHP function that can be stored in a variable and passed as an argument to other functions or methods. A closure is a lambda function that is aware of its surrounding context.
2
Likes
Stuart Todd
•
2 years ago
•
Best Practices
What is a Lambda function?
A lambda function is an anonymous PHP function that can be stored in a variable and passed as an argument to other functions or methods. A closure is a Lambda function that is aware of its surrounding context.
I personally use Lambdas to bootstrap / configure my projects. If you're familar with frameworks such as Laravel, you'll see them all over!
Function accepting the Lambda as a parameter
Notice the $fn parameter below.
use Closure;
function whos_eating_what(array $names, Closure $fn): array {
$output = [];
foreach ($names as $name) {
$output[] = $name . ' is eating ' . $fn($name);
}
return $output;
}
The Lambda
Code below generates different output (of the same method) at run-time by passing in different Lambdas.
$names = [
'Stu',
'Cheryl',
'Millie',
'Harry',
'Murphy',
'Milo',
];
$version1 = whos_eating_what($names, function ($name) {
$mappings = [
'Stu' => 'Nandos',
'Cheryl' => 'Beans on toast',
'Millie' => 'KFC',
'Harry' => 'Burger King',
];
if (! empty($mappings[$name])) {
return $mappings[$name];
}
return 'Anything!';
});
$version2 = whos_eating_what($names, function ($name) {
$mappings = [
'Stu' => 'Salad',
'Cheryl' => 'Beans on toast',
'Millie' => 'KFC',
'Harry' => 'Burger King',
];
if (! empty($mappings[$name])) {
return $mappings[$name];
}
return 'Dog food';
});
dd($version1, $version2);
Output
P.S - No way I'm eating salad (but I probably should)...