PHP 中的箭头函数是在 PHP 7.4 中引入的。他们是一个有点不同.
fn 关键字
The new fn
关键字是现在是保留关键字 https://github.com/php/php-src/commit/f3e5bbe6f37ce52a9ecd42812389e6aaf3aa2892#diff-7748eb3bfdd3bf962553f6f9f2723c45.
之前我们一直使用function
关键词。
$add = function ($valone,$valtwo) {
return $valone + $valtwo;
};
$add(1,2) // 3
随着新箭头函数的出现:
$add = fn($valone,$valtwo) => $valone + $valtwo;
$add(1,2) // 3
父范围
之前,我们必须遵循关键字的用法use
为了变量的参与来自父范围。
$y = 1;
$fn = function ($x) use ($y) {
return $x + $y;
};
echo $fn(2); // 3
父作用域中定义的表达式将是隐含地按值捕获。
$y = 1;
$fn = fn($x) => $x + $y;
echo $fn(2); // 3
上面的内容如下$this
类方法内的变量。
class foo {
public function test() {
$context = fn() => var_dump($this);
$context();
}
}
$test = new foo();
$test->test(); // object(foo)#1 (0) { }
就像以前一样,我们过去常常使用use
关键字从父作用域获取变量,因此这意味着我们不能将函数中的变量值写入上层作用域。
$y = 1;
$fn = fn() => $y++;
$fn(); // Has no effect
echo $y // 1
如果我们正在考虑从闭包中分配另一个变量的值,那么这也行不通
$y = 1;
$f = 0;
$fn = fn() => $f = $y + 1;
$fn();
echo $f; // 0
函数签名
这在 PHP 中是全新的,它允许我们定义函数、变量的类型和函数返回的值
fn(int $x) => $x; // the argument type must be (int)
fn(): int => $x; // type of return value (int)
如果调用函数时未将定义的参数类型放入参数中,则会引发错误。可以使用以下命令捕获错误TypeError
type
$var = 10;
$int_fn = fn(int $x): int => $x;
var_dump($int_fn($var)); // int(10)
try {
$int_fn("foo");
} catch (TypeError $e) {
echo $e->getMessage(), "\n"; // Argument 1 passed to {closure}() must be of the type int, string given, called in x on line y
}
到 PHP 7.1,他们支持?type
在参数中也允许参数为空。
$funn = fn(?int... $args): array => $args;
var_dump($funn(20, null, 30)); // Array(3) { [0]=> int(20) [1]=> NULL [2]=> int(30) }
如果您向上述函数提供字符串或其他任何内容而不是 int,那么您将收到错误
传递给 {closure}() 的参数必须是 int 或 null 类型,给定字符串,在第 y 行的 x 中调用
嵌套箭头函数
$var = 6;
var_dump((fn() => fn() => $var)()()); // int(6)
var_dump((fn() => function() use($var) { return $var; })()()); // int(6)
闭包内任何可能的错误没有被抛出除非被叫
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$b = 1;
fn() => $b + $c; // no error, nothing
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$b = 1;
(fn() => $b + $c)(); // Notice: Undefined variable: c in the location on line x
如果错误报告关闭那么你就会得到int(1)
如何使用 PHP。现在7.4了?
用于快速在线测试 https://3v4l.org/只需将这些代码粘贴到那里即可
对于您的本机系统,我刚刚克隆php-src 的这个分支 https://github.com/php/php-src/tree/PHP-7.4并使用 GCC 和 make 编译它。我通过 test.php 文件和命令行进行了测试,以检查一切是否正常。
核心参考——https://wiki.php.net/rfc/arrow_functions_v2 https://wiki.php.net/rfc/arrow_functions_v2