Skip to content

Instantly share code, notes, and snippets.

@woprrr
Created March 5, 2020 09:46
Show Gist options
  • Save woprrr/baec829efee0bca024874222a6e3c8db to your computer and use it in GitHub Desktop.
Save woprrr/baec829efee0bca024874222a6e3c8db to your computer and use it in GitHub Desktop.
PHP 7.4 Arrow Functions 2.0 `Short Closures` examples. Try it now : https://3v4l.org/C3UfN
<?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));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment