站长资讯网
最全最丰富的资讯网站

PHP中箭头函数的实例详解

PHP中箭头函数的实例详解

称为箭头函数的短闭包是PHP7.4版本将带来的期待已久的功能之一。它是由 Nikita Popov、Levi Morrison 和 Bob Weinand 提出的,你可以在此处阅读原 RFC

相关学习推荐:PHP编程从入门到精通

摘自 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));

让我们来看看规则吧

  1. fn 是关键字,而不是保留的函数名称。
  2. 它只能有一个表达式,那就是 return 语句。
  3. 不需要使用rereturnuse关键字。
  4. $this 变量,作用域和 LSB 作用域自动绑定。
  5. 你可以键入提示参数和返回类型。
  6. 你甚至可以使用引用&和 展开操作符 ...

几个例子

//作用域示例 $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;

未来范围

  1. 多行箭头函数
  2. 允许对类内的函数使用箭头函数。
//现今 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; }

我最喜欢的要点

  1. 回调可以更短
  2. 不需要use关键字便问变量。

让我知道你对这些更新有什么看法,你最喜欢的收获是什么?

感谢阅读。

赞(0)
分享到: 更多 (0)