称为箭头函数的短闭包是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));
让我们来看看规则吧fn 是关键字,而不是保留的函数名称。它只能有一个表达式,那就是 return 语句。不需要使用rereturn和use关键字。$this 变量,作用域和 lsb 作用域自动绑定。你可以键入提示参数和返回类型。你甚至可以使用引用&和 展开操作符 ...几个例子//作用域示例$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;}
我最喜欢的要点回调可以更短不需要use关键字便问变量。让我知道你对这些更新有什么看法,你最喜欢的收获是什么?
感谢阅读。
以上就是php中箭头函数的实例详解的详细内容。