What is the Void Return Type in PHP?
This article explores the void return type introduced in
modern PHP, explaining what it is, why it was introduced, and how to use
it correctly in your code. You will learn the syntax rules, see
practical code examples, and understand how this type hint improves code
quality and type safety in PHP applications.
Understanding the Void Return Type
Introduced in PHP 7.1, the void return type is a type
hint used to specify that a function or method performs an action but
does not return a value. By declaring a function with a
: void return type, you explicitly state to the PHP engine
and other developers that the output of this function should not be
captured or expected.
Syntax and Rules
To use the void return type, append : void
after the function’s parameter list. When a function is declared with a
void return type, it must adhere to the following strict
rules:
- No return values: The function cannot return any
value. Writing
return $value;will trigger a fatal compiler error. - Empty return statements are allowed: You can use an
empty
return;statement. This is useful for exiting a function early. - No explicit null returns: You cannot write
return null;. Even though a void function technically evaluates tonullif its output is forced into a variable, explicitly returningnullviolates thevoidtype contract and causes a fatal error.
Code Examples
Here is an example of a correct implementation of the
void return type:
function logMessage(string $message): void {
echo $message;
// No return statement is needed, but an empty "return;" is allowed
}
function processOrder(int $orderId): void {
if ($orderId <= 0) {
return; // Valid: early exit without a value
}
// Process the order here
}Conversely, the following examples are invalid and will cause a fatal error in PHP:
// INVALID: Cannot return a value
function redirectUser(string $url): void {
return true;
}
// INVALID: Cannot explicitly return null
function calculateData(): void {
return null;
}Why Use the Void Return Type?
Using the void return type provides several key benefits
for modern PHP development:
- Improved Code Readability: It immediately informs developers reading the code that the function is executed solely for its side effects (such as writing to a database, modifying a file, or rendering output) rather than producing a result.
- Enhanced Type Safety: PHP will prevent you from accidentally returning data from a function that should not produce any.
- Better Static Analysis: Tools like PHPStan, Psalm,
and modern IDEs can flag logical errors, such as attempting to assign
the result of a
voidfunction to a variable.