With all the power of function parameter types and function return types introduced in PHP 7, there was one thing missing from the mix
function. While function return types allowed specifying a desired return type, they did not allow specifying the lack of return value. To address this inconsistency, the PHP 7.1 release introduced a void
return type feature.
Why is this important, we might ask ourselves? As with previously mentioned function return types, this feature can be extremely useful for documentation and error-checking purposes. By its nature, PHP does not require a return
statement in its function definitions, making it unclear at first look if the function simply executes certain actions or returns a value. Using the void
return type makes it clearer that a function's purpose is to perform an action, rather than producing a result.
Let's take a look at the following example:
function A(): void { // valid } function B(): void { return; // valid } function C(): void { return null; // invalid } function D(): void { return 1; // invalid }
The function A
and function B
methods showcase a valid use of the void
type parameter. The function A
method has no explicitly set return value, but that's OK, as PHP implicitly always returns null.
The function B
method simply uses the return
statement without any following type, which also makes it valid. The function C
method is a bit strange, as it looks like it might be valid at first, but it's not. How is it that function C
is invalid while the function A
method is, even though they do the same thing? Even though return
and return null
are technically equivalent in PHP, they are not really the same. The existence of a return type, or its lack, denotes a function intent. Specifying return values, even if its null
, suggests the value is significant. With a void return type, the return value is insignificant. The use of the void
return type, therefore, signifies an unimportant return value, the one that won’t be used anywhere after the function is called.
Note
The differentiation between explicit void and implicit null return might come as somewhat foggy. The takeaway here is that using void return types conveys that the function is not supposed to return any kind of value. While they do not make any major impact on the code itself, and their use is fully optional, they do bring a certain richness to the language.