Skip to content

Commit 73b2f79

Browse files
committed
More explicit errors for return; vs return null;
Both for "return null" in a void function and "return" in a nullable return function.
1 parent fe90756 commit 73b2f79

File tree

3 files changed

+30
-4
lines changed

3 files changed

+30
-4
lines changed

Zend/tests/return_types/void_disallowed1.phpt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,4 @@ function foo(): void {
99

1010
// Note the lack of function call: function validated at compile-time
1111
--EXPECTF--
12-
Fatal error: A void function must not return a value in %s on line %d
12+
Fatal error: A void function must not return a value (did you mean "return;" instead of "return null;"?) in %s on line %d
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
--TEST--
2+
Nullable typed return without value generates friendlier error message
3+
--FILE--
4+
<?php
5+
6+
function test() : ?int {
7+
return;
8+
}
9+
10+
test();
11+
12+
?>
13+
--EXPECTF--
14+
Fatal error: A function with return type must return a value (did you mean "return null;" instead of "return;"?) in %s on line %d

Zend/zend_compile.c

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2270,7 +2270,13 @@ static void zend_emit_return_type_check(
22702270
/* `return ...;` is illegal in a void function (but `return;` isn't) */
22712271
if (return_info->type_hint == IS_VOID) {
22722272
if (expr) {
2273-
zend_error_noreturn(E_COMPILE_ERROR, "A void function must not return a value");
2273+
if (expr->op_type == IS_CONST && Z_TYPE(expr->u.constant) == IS_NULL) {
2274+
zend_error_noreturn(E_COMPILE_ERROR,
2275+
"A void function must not return a value "
2276+
"(did you mean \"return;\" instead of \"return null;\"?)");
2277+
} else {
2278+
zend_error_noreturn(E_COMPILE_ERROR, "A void function must not return a value");
2279+
}
22742280
}
22752281
/* we don't need run-time check */
22762282
return;
@@ -2280,8 +2286,14 @@ static void zend_emit_return_type_check(
22802286
zend_op *opline;
22812287

22822288
if (!expr && !implicit) {
2283-
zend_error_noreturn(E_COMPILE_ERROR,
2284-
"A function with return type must return a value");
2289+
if (return_info->allow_null) {
2290+
zend_error_noreturn(E_COMPILE_ERROR,
2291+
"A function with return type must return a value "
2292+
"(did you mean \"return null;\" instead of \"return;\"?)");
2293+
} else {
2294+
zend_error_noreturn(E_COMPILE_ERROR,
2295+
"A function with return type must return a value");
2296+
}
22852297
}
22862298

22872299
if (expr && expr->op_type == IS_CONST) {

0 commit comments

Comments
 (0)