Skip to content
Marcel Kloubert edited this page Oct 8, 2015 · 5 revisions

Lambda expression

A lambda expression is a callable as string that will be converted to a closure.

The following function

function ($a, $b) {
    return $a + $b;
}

can be translated to

($a, $b) => $a + $b

or shorter

$a, $b => $a + $b

If you need more lines for the function body, you can simply use brackets ({}):

($a, $b) => {
    $sum = $a + $b;

    return $sum;
}

Lambdas without arguments

A function that has no arguments

function () {
    return mt_rand();
}

can be translated to

() => mt_rand()

Best practise

Only use ' (single quotes) to define a lambda expression:

$calSum = '($a, $b) => $a + $b';

Otherwise you can (and will) get problems with the "variable parsing" feature of PHP if you use double quotes (")!

Outer variables

It is NOT possible to use outer variables from execution context!

Use a closure instead.

Clone this wiki locally