Home >Backend Development >PHP Tutorial >Detailed explanation of examples of arrow functions in PHP
#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
//老办法 $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));
fn
is the key words instead of reserved function names. rereturn
and use
keywords. $this
Variables, scopes and LSB scopes are automatically bound. &
and the spread operator ...
//作用域示例 $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;
//现今 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 } } //也许在未来的某一天 class Test { private $foo; private $bar; fn getFoo() => $this->foo; fn getBar() => $this->bar; }
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!