稱為箭頭函數(shù)的短閉包是PHP7.4
版本將帶來的期待已久的功能之一。它是由 Nikita Popov、Levi Morrison 和 Bob Weinand 提出的,你可以在此處閱讀原 RFC
相關(guān)學(xué)習(xí)推薦:PHP編程從入門到精通
摘自 Doctrine DBAL 的快速示例
//老辦法 $this->existingSchemaPaths = array_filter($paths, function ($v) use ($names) { return in_array($v, $names); }); // 使用箭頭函數(shù)的新方法 $this->existingSchemaPaths = array_filter($paths, fn($v) => in_array($v, $names));
讓我們來看看規(guī)則吧
fn
是關(guān)鍵字,而不是保留的函數(shù)名稱。- 它只能有一個(gè)表達(dá)式,那就是 return 語句。
- 不需要使用
rereturn
和use
關(guān)鍵字。 $this
變量,作用域和 LSB 作用域自動(dòng)綁定。- 你可以鍵入提示參數(shù)和返回類型。
- 你甚至可以使用引用
&
和 展開操作符...
幾個(gè)例子
//作用域示例 $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; //有效的函數(shù)簽名 fn(array $x) => $x; fn(): int => $x; fn($x = 42) => $x; fn(&$x) => $x; fn&($x) => $x; fn($x, ...$rest) => $rest;
未來范圍
- 多行箭頭函數(shù)
- 允許對(duì)類內(nèi)的函數(shù)使用箭頭函數(shù)。
//現(xiàn)今 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; }
我最喜歡的要點(diǎn)
- 回調(diào)可以更短
- 不需要
use
關(guān)鍵字便問變量。
讓我知道你對(duì)這些更新有什么看法,你最喜歡的收獲是什么?
感謝閱讀。