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:

  1. No return values: The function cannot return any value. Writing return $value; will trigger a fatal compiler error.
  2. Empty return statements are allowed: You can use an empty return; statement. This is useful for exiting a function early.
  3. No explicit null returns: You cannot write return null;. Even though a void function technically evaluates to null if its output is forced into a variable, explicitly returning null violates the void type 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: