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
是关键字,而不是保留的函数名称。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
关键字便问变量。看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。