
#Short closures called arrow functions are one of the long-awaited features that will be brought to version PHP7.4
. It was proposed by Nikita Popov, Levi Morrison and Bob Weinand. You can read the original RFC here
Related learning recommendations:PHP Programming from Beginner to Master
Quick example taken from Doctrine DBAL
1 2 3 4 5 6 7 | $this ->existingSchemaPaths = array_filter ( $paths , function ( $v ) use ( $names ) {
return in_array( $v , $names );
});
$this ->existingSchemaPaths = array_filter ( $paths , fn( $v ) => in_array( $v , $names ));
|
Copy after login
Let’s look at the rules
fn
is the key words instead of reserved function names. - It can only have one expression, that is the return statement.
- No need to use the
rereturn
and use
keywords. $this
Variables, scopes and LSB scopes are automatically bound. - You can type prompt parameters and return types.
- You can even use references
&
and the spread operator ...
##A few examples
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | $discount = 5;
$items = array_map (fn( $item ) => $item - $discount , $items );
$users = array_map (fn(User $user ): int => $user ->id, $users );
function complement(callable $f ) {
return fn(... $args ) => ! $f (... $args );
}
$z = 1;
$fn = fn( $x ) => fn( $y ) => $x * $y + $z ;
fn( array $x ) => $x ;
fn(): int => $x ;
fn( $x = 42) => $x ;
fn(& $x ) => $x ;
fn&( $x ) => $x ;
fn( $x , ... $rest ) => $rest ;
|
Copy after login
Future Scope
Multiline Arrow FunctionsAllows the use of arrow functions for functions within a class. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class Test {
public function method() {
$fn = fn() => var_dump( $this );
$fn ();
$fn = static fn() => var_dump( $this );
$fn ();
}
}
class Test {
private $foo ;
private $bar ;
fn getFoo() => $this ->foo;
fn getBar() => $this ->bar;
}
|
Copy after login
My favorite points
Callbacks can be shorter- No need for the
- use
keyword to ask for variables.
Let me know what you think of these updates and what was your favorite takeaway?
Thanks for reading. The above is the detailed content of Detailed explanation of examples of arrow functions in PHP. For more information, please follow other related articles on the PHP Chinese website!