<?php
# Arrow Functions 2.0 `Short Closures`
# OLD WAY (PHP < 7.4 )
function cube($arg){
return ($arg * $arg * $arg);
}
$b = array_map('cube', range(1, 5));
var_dump('Short closure old syntax', $b);
# OR
$b = array_map(function($a2) {return ($a2 * $a2 * $a2);}, range(1, 5));
var_dump('Short closure old syntax variant', $b);
# ONLY FOR PHP 7.4 +
#/!\ MORE CLEAR PHP CODE BEST PRACTIVE /!\
$b = array_map(fn($n) => $n * $n * $n, range(1, 5));
var_dump('Arrow Function 7.4 + syntax', $b);
# OLD Example with closure herit in parent scope with `use` syntax
$factor = 10;
$oldcalc = function(int $num) use ($factor): int {
return $num * $factor;
};
var_dump('Short closure old syntax', $oldcalc(2));
# PHP 7.4 + syntax it allows us to build more readable and maintainable code.
$oldcalc = fn(int $num): int => $num * $factor;
var_dump('Arrow Function 7.4 + syntax', $oldcalc(2));
- Output for 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.26, 8.4.1 - 8.4.13
- string(24) "Short closure old syntax"
array(5) {
[0]=>
int(1)
[1]=>
int(8)
[2]=>
int(27)
[3]=>
int(64)
[4]=>
int(125)
}
string(32) "Short closure old syntax variant"
array(5) {
[0]=>
int(1)
[1]=>
int(8)
[2]=>
int(27)
[3]=>
int(64)
[4]=>
int(125)
}
string(27) "Arrow Function 7.4 + syntax"
array(5) {
[0]=>
int(1)
[1]=>
int(8)
[2]=>
int(27)
[3]=>
int(64)
[4]=>
int(125)
}
string(24) "Short closure old syntax"
int(20)
string(27) "Arrow Function 7.4 + syntax"
int(20)
- Output for 7.3.0 - 7.3.33
- Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ')' in /in/C3UfN on line 18
Process exited with code 255. - Output for 7.2.0 - 7.2.33
- Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ',' or ')' in /in/C3UfN on line 18
Process exited with code 255.
preferences:
155.86 ms | 409 KiB | 5 Q