如何在PHP中使用箭头功能? [英] How to use arrow functions in PHP?

查看:284
本文介绍了如何在PHP中使用箭头功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解了PHP 7.4中的箭头功能.我尝试像这样使用它们

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

因为在拉取请求中看到了=>运算符.就像JavaScript.

我希望输出为"2",但这没有用!我

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

解决方案

PHP 7.4中引入了箭头函数.它们是稍有不同.

fn关键字

新的fn关键字为现在是保留关键字.

以前,我们曾经继续使用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关键字从父作用域中获取变量来执行操作,因此这意味着我们无法将函数中变量的值写入上层作用域./p>

$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,则会出现错误消息

传递给{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吗?
要进行快速在线测试,只需将这些代码粘贴到此处

对于您的本机系统,我只是克隆了此php- src 并使用GCC和make对其进行编译.我通过test.php文件和命令行进行了测试,以检查是否一切正常.

核心参考- https://wiki.php.net/rfc/arrow_functions_v2

I got to know about arrow functions in PHP 7.4. I tried using them like

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

Because I saw the => operator in the pull request. Just like javascript.

I expected '2' as the output but this didn't work! I got

Parse error: syntax error, unexpected ')' in /test.php on line 3

解决方案

Arrow functions in PHP are introduced in PHP 7.4. They are a little different.

The fn keyword

The new fn keyword is now a reserved keyword.

Previously, we used to continue using function keyword.

$add = function ($valone,$valtwo) {
    return $valone + $valtwo;
};
$add(1,2) // 3

With the advent of new arrow functions:

$add = fn($valone,$valtwo) => $valone + $valtwo;
$add(1,2) // 3

Parent scope

Earlier, we have to follow with the usage of the keyword use for the involvement of a variable from the parent scope.

$y = 1;
$fn = function ($x) use ($y) {
    return $x + $y;
};
echo $fn(2); // 3

The expression defined in the parent scope will be implicitly captured by-value.

$y = 1;
$fn = fn($x) => $x + $y;
echo $fn(2); // 3

The above follows for $this variable inside class methods.

class foo {
   public function test() {
       $context = fn() => var_dump($this);
       $context(); 
   }
}
$test = new foo();
$test->test();  // object(foo)#1 (0) { }

Just like previously, we used to perform our operations by using the use keyword to take a variable from the parent scope, so this means that we cannot write the value of the variable from the function into the upper scope.

$y = 1;
$fn = fn() => $y++;
$fn(); // Has no effect
echo $y  // 1

If we are thinking of assigning another variable's value from the closure then this also will not work

$y = 1;
$f = 0;
$fn = fn() => $f = $y + 1;
$fn();
echo $f; // 0


Function signatures

This is completely new in PHP, this allows us the define the type of function, variable and the value the function is returning

fn(int $x) => $x; // the argument type must be (int)
fn(): int => $x; // type of return value (int)

Errors are thrown when the defined argument type is not placed in the argument when calling the function. The error can be caught by using the 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
}

By PHP 7.1, they support the ?type in arguments which allows the argument to be null too.

$funn = fn(?int... $args): array => $args;
var_dump($funn(20, null, 30)); // Array(3) { [0]=> int(20) [1]=> NULL [2]=> int(30) }

If you supply a string or anything else rather than int to the above function, then you'll get an error

Argument passed to {closure}() must be of the type int or null, string given, called in x on line y

Nested arrow functions

$var = 6;
var_dump((fn() => fn() => $var)()());  // int(6)
var_dump((fn() => function() use($var) { return $var; })()()); // int(6)

Any possible errors inside the closure are not thrown unless called

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

If error reporting is off then you'll just get int(1)

How to use PHP. 7.4 now?
For quick online testing just paste these code there

For your native system, I Just cloned this branch of php-src and compiled it using GCC and make. I did my testing via a test.php file and command line to check if everything works.

Core reference - https://wiki.php.net/rfc/arrow_functions_v2

这篇关于如何在PHP中使用箭头功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆