如何在PHP中使用箭头函数?

2024-01-23

我开始了解PHP 7.4 中的箭头函数 https://github.com/php/php-src/pull/3941。我尝试像这样使用它们

<?php
$num = 1;
$arrowfunction = () => {
   return $num + 1;
}
echo $arrowfunction();

因为我看到了=>拉取请求中的运算符。就像 JavaScript 一样。

我期望输出为“2”,但这不起作用!我有

解析错误:语法错误,/test.php 第 3 行出现意外的“)”


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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在PHP中使用箭头函数? 的相关文章

随机推荐