Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. I think, that I am missing something. Can you help me.

Example 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:

<?php

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

throws the same Exception. I understand, that example 2 throws an exception because it is an implicit return. How is that for explicit calling a method/function with void return type hinting?

Why? I'd like to be specific in return types. Makes live easier with ide and debugging.

Is it not possible to return void in arrow functions? Am I missing something? Is this not documented?

like image 589
phylogram Avatar asked Sep 19 '25 00:09

phylogram


1 Answers

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.

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).

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();
like image 97
Rain Avatar answered Sep 21 '25 16:09

Rain