简体   繁体   English

不能使用带有返回 void 类型提示的箭头 function

[英]Can not use an arrow function with return void type hinting

Using arrow functions in php 7.4 with return type hinting void results in a php fatal error.在 php 7.4 中使用带有返回类型提示 void 的箭头函数会导致 php 致命错误。 I think, that I am missing something.我想,我错过了一些东西。 Can you help me.你能帮助我吗。

Example 1:示例 1:

<?php

function returnvoid(): void {
    echo 'I am here, but do not return anything aka void';
}

$arrow_function = fn(): void => returnvoid();

$arrow_function();

results in结果是

PHP Fatal error:  A void function must not return a value in [my_filesystem]/.config/JetBrains/PhpStorm2020.1/scratches/scratch_3.php on line 7

also Example 2:还有示例2:

<?php

$f = fn(): void => 1;

throws the same Exception.抛出相同的异常。 I understand, that example 2 throws an exception because it is an implicit return.我了解,示例 2 引发异常,因为它是隐式返回。 How is that for explicit calling a method/function with void return type hinting?使用 void 返回类型提示显式调用方法/函数如何?

Why?为什么? I'd like to be specific in return types.我想具体说明返回类型。 Makes live easier with ide and debugging.使用 ide 和调试使生活更轻松。

Is it not possible to return void in arrow functions?箭头函数不能返回 void 吗? Am I missing something?我错过了什么吗? Is this not documented?这没有记录吗?

An arrow function is meant to make the syntax more concise for single-expression closures.It can only have one expression, which is the return .箭头 function旨在使单表达式闭包的语法更简洁。它只能有一个表达式,即return

It's usually used in functions like array_map or array_filter , so using an arrow function with void type is not possible and also makes no sense (You already created the returnvoid function).它通常用于array_map或 array_filter 之类的函数,因此使用带有void类型的箭头array_filter是不可能的,也没有意义(您已经创建了returnvoid函数)。

For your purpose, you can still use anonymous functions出于您的目的,您仍然可以使用匿名函数

function returnvoid(): void {
    echo 'I am here, but do not return anything aka void';
}

$anonymous_function = function() : void {
    returnvoid();
};

$anonymous_function();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM