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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With