天天看点

php 横杠箭头,PHP 中的箭头函数(Arrow Functions)

php 横杠箭头,PHP 中的箭头函数(Arrow Functions)

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

摘自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 语句。

不需要使用 return 和 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 关键字便问变量。

感谢阅读。