我开始了解 arrow functions in PHP 7.4 .我试过像这样使用它们
<?php
$num = 1;
$arrowfunction = () => {
return $num + 1;
}
echo $arrowfunction();
因为我在拉取请求中看到了 =>
运算符。就像javascript一样。
我希望输出“2”,但这没有用!我得到了
Parse error: syntax error, unexpected ')' in /test.php on line 3
最佳答案
PHP 中的箭头函数是在 PHP 7.4 中引入的。它们有点不同。
fn 关键字
新的 fn
关键字是 now a reserved keyword .
以前,我们习惯于继续使用 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
类型
$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
,这也允许参数为 null。
$funn = fn(?int... $args): array => $args;
var_dump($funn(20, null, 30)); // Array(3) { [0]=> int(20) [1]=> NULL [2]=> int(30) }
如果你向上面的函数提供一个字符串或其他任何东西而不是 int,那么你会得到一个错误
Argument passed to {closure}() must be of the type int or null, string given, called in x on line y
嵌套箭头函数
$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了?
For quick online testing只需将这些代码粘贴到那里
对于你的本地系统,我刚刚克隆了this branch of php-src并使用 GCC 和 make 编译它。我通过 test.php 文件和命令行进行了测试,以检查是否一切正常。
关于php - 如何在 PHP 中使用箭头函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56657135/