DEV Community

arasosman
arasosman

Posted on Originally published at mycuriosity.blog

How to Use PHP's Never Return Type

The Solution

Here's how to use the never return type for functions that never return to the caller:

<?php

function terminateApplication(string $message): never {
    echo "Critical error: " . $message;
    exit(1);
}

function redirectAndExit(string $url): never {
    header("Location: " . $url);
    exit();
}

function throwException(string $error): never {
    throw new RuntimeException($error);
}

// Usage examples
if ($criticalError) {
    terminateApplication("Database connection failed");
    // This line is never reached
}

if (!$user->isAuthorized()) {
    redirectAndExit("/login");
    // Code after this is unreachable
}

try {
    validateInput($data);
} catch (Exception $e) {
    throwException("Validation failed: " . $e->getMessage());
}
Enter fullscreen mode Exit fullscreen mode

Why This Works

The never return type serves as a contract that tells PHP and other developers:

  1. Function Never Returns: The function will always terminate execution through exit(), die(), or throwing an exception
  2. Static Analysis: Tools can detect unreachable code after these function calls
  3. Type Safety: PHP enforces that functions declared with never must actually never return

Common Use Cases:

  • Functions that call exit() or die()
  • Functions that always throw exceptions
  • Functions that redirect and terminate
  • Error handlers that stop execution

The never type makes your code's intent crystal clear and helps prevent bugs from unreachable code assumptions.

Top comments (1)

Collapse
 
jamey_h66 profile image
Jamey H

Nice posting, Can we talk? Could you share your email address?