Arrow Functions in PHP
Rishiraj Purohit
Posted on August 26, 2019
Inspired from Javascript's arrow function, I guess?
es6-in-depth-arrow-functions
The short closures called arrow functions are one of the long due functionalities that PHP 7.4
will bring. It is proposed by Nikita Popov, Levi Morrison, and Bob Weinand and you can read the original RFC here
Quick Example taken from Doctrine DBAL
//old way
$this->existingSchemaPaths = array_filter($paths, function ($v) use ($names) {
return in_array($v, $names);
});
//new way with arrow function
$this->existingSchemaPaths = array_filter($paths, fn($v) => in_array($v, $names));
Let's go through the rules
-
fn
is a keyword and not a reserved function name. - It can have only 1 expression and that is the return statement.
- No need to use
return
anduse
keywords. -
$this
variable, the scope and the LSB scope are automatically bound. - You can type-hint the arguments and return types.
- You can even use references
&
and spread operator...
Few examples
//scope example
$discount = 5;
$items = array_map(fn($item) => $item - $discount, $items);
//type hinting
$users = array_map(fn(User $user): int => $user->id, $users);
//spread operator
function complement(callable $f) {
return fn(...$args) => !$f(...$args);
}
//nesting
$z = 1;
$fn = fn($x) => fn($y) => $x * $y + $z;
//valid function signatures
fn(array $x) => $x;
fn(): int => $x;
fn($x = 42) => $x;
fn(&$x) => $x;
fn&($x) => $x;
fn($x, ...$rest) => $rest;
Future Scope
- Multi-line arrow functions
- Allow arrow notation for real functions inside a class.
//valid now
class Test {
public function method() {
$fn = fn() => var_dump($this);
$fn(); // object(Test)#1 { ... }
$fn = static fn() => var_dump($this);
$fn(); // Error: Using $this when not in object context
}
}
//maybe someday in future
class Test {
private $foo;
private $bar;
fn getFoo() => $this->foo;
fn getBar() => $this->bar;
}
My Favorite takeaways
- Callbacks can be shorter
- No need for
use
keyword, you can access variables.
Let me know what do you think about these updates and what are your favorite takeaways from this?
till next time, rishiraj purohit
💖 💪 🙅 🚩
Rishiraj Purohit
Posted on August 26, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
symfony Symfony Station Communiqué — 15 November 2024. A look at Symfony, Drupal, PHP, and programming news!
November 18, 2024