Development Blog

Collection of development articles I've put together...
Return to articles

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
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

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

$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