-
-
Notifications
You must be signed in to change notification settings - Fork 13
Lambda expression
Marcel Kloubert edited this page Oct 8, 2015
·
5 revisions
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;
}
A function that has no arguments
function () {
return mt_rand();
}
can be translated to
() => mt_rand()
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 ("
)!
It is NOT possible to use outer variables from execution context!
Use a closure instead.