Void

void は、関数が値を返さないことを示す、 戻り値のみで指定できる型ですが、関数を終了させても構いません。 よって、この型は union 型 の一部として指定することが出来ません。 PHP 7.1.0 以降で利用できます。

注意: 戻り値の型が void である関数であっても、 値を返すことはできます。その場合には、戻り値は常に null になります。

add a note

User Contributed Notes 1 note

up
0
harl at gmail dot com
1 day ago
"Even if a function has a return type of void it will still return a value, this value is always null."

Syntactically, a void-returning function's return statements must be plain `return;`. If the function is declared as returning null then the return statement needs to include a return value: `return null;`.

A function that always returns null ("function foo(): null {...}") is equivalent to a void-returning function ("function foo(): void {...}"). Neither actually returns any information to the caller (the caller always receives null, and doesn't learn anything from it).

Meaningful return type declarations using null are always union types. "function foo(): null" is legal but pointless and might as well be written as returning void to make explicit the fact that it doesn't return anything meaningful (and indicates that "$v = foo();" is certainly a mistake of some sort.) The exception to this is if foo() is a subclass method overriding a wider-but-still-nullable type from a superclass.

(And the technical reason why a void function still returns null is that a function call is an expression so needs to have SOME value if it returns at all.)
To Top