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
Top comments (1)
It would be really great if they implemented the arrow functions RFC!
I came across it today because I'm a .Net+JS dev helping a colleague to write a PHP app talking to our API. And I knew he would need to do something like
.Where
from LINQ or.filter
from JS.So I found the PHP functions like
array_filter
, but with the long closures syntax it's just so much code! And like you say, you need theuse ()
clause. It's messy. Arrow functions would be brilliant in PHP.Thanks for the post!