PHP 8.1 introduced never for functions that cannot return normally.
What It Does
PHP 8.1 introduced never for functions that cannot return normally. The following examples distinguish a normal use case, a boundary case and a practical application.
Requirements and Compatibility
PHP 8.1 or later.
PHP 8.1 introduced enums, fibers and readonly properties. Features shown in newer snippets may require a later PHP version.
The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.
Example 1: Basic Behavior
Start with the smallest meaningful working case.
<?php
function stopProcessing(string $reason): never { throw new RuntimeException($reason); }
try { stopProcessing('Invalid workflow'); } catch (RuntimeException $e) { echo $e->getMessage(); }
Example 2: Another Case
Examine the edge case and the observable result.
<?php
function rejectRequest(int $status): never { http_response_code($status); exit; }
if (false) rejectRequest(403);
echo 'Execution continues only when allowed';
Practical Example: Putting It to Use
Apply the technique to a small practical task.
<?php
function impossibleState(string $state): never { throw new LogicException('Unexpected: ' . $state); }
try { impossibleState('archived'); } catch (LogicException $e) { echo 'Rejected unsupported state'; }
Important Behavior and Edge Cases
A never function must exit or throw; a return statement is not valid.
Comparison with Related Functions or Approaches
| Option | What it means in practice |
|---|---|
| 8.1 Never Return Type | PHP 8.1 introduced never for functions that cannot return normally. |
| Related approach | Use void for functions that return control without a value. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the important boundary for 8.1 Never Return Type | A never function must exit or throw; a return statement is not valid. |
| Assuming a related mechanism has the same behavior | Use void for functions that return control without a value. |
Key Takeaways
- PHP 8.1 introduced never for functions that cannot return normally.
- A never function must exit or throw; a return statement is not valid.
- Use void for functions that return control without a value.
Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.