I found in here the new spec: https://wiki.php.net/rfc/void_return_type
function lacks_return(): void {
// valid
}
function returns_nothing(): void {
return; // valid
}
function returns_void(): void {
return void; // valid
}
Ask: Do you know what happens behind the scene. Will the lacks_return
function return actually void
?
You could have tested this yourself pretty easily:
function lacks_return(): void {
}
function returns_nothing(): void {
return;
}
echo gettype(lacks_return()); // NULL
echo gettype(returns_nothing()); // NULL
So the answer is yes - there is an implicit empty (null) return so you could either use an empty return or skip it completely. Which kind of makes sense - returning nothing is the same as not returning anything?
Behind the scenes, PHP checks for return
statements in void
functions and, if they specify a return value, throws a compile-time error:
/* `return ...;` is illegal in a void function (but `return;` isn't) */
if (return_info->type_hint == IS_VOID) {
if (expr) {
if (expr->op_type == IS_CONST && Z_TYPE(expr->u.constant) == IS_NULL) {
zend_error_noreturn(E_COMPILE_ERROR,
"A void function must not return a value "
"(did you mean \"return;\" instead of \"return null;\"?)");
} else {
zend_error_noreturn(E_COMPILE_ERROR, "A void function must not return a value");
}
}
/* we don't need run-time check */
return;
}
Otherwise, compilation of void
functions works like normal. return
without a value implicitly returns NULL
:
if (!expr_ast) {
expr_node.op_type = IS_CONST;
ZVAL_NULL(&expr_node.u.constant);
And every function is compiled with an implicit return
at the end:
zend_emit_final_return(0);
zn.op_type = IS_CONST;
if (return_one) {
ZVAL_LONG(&zn.u.constant, 1);
} else {
ZVAL_NULL(&zn.u.constant);
}