never Return Type (PHP 8.1)
debt(d5/e1/b1/t5)
Closest to 'specialist tool catches it' (d5). The detection_hints list PHPStan, Psalm, and Rector — all specialist static analysis tools, not default linters or compilers. PHPStan can report unreachable code that should be caught by never, and flag functions that always throw without the never return type, but this requires running a dedicated SAST tool rather than a built-in compiler check or default linter.
Closest to 'one-line patch or single-call swap' (e1). The quick_fix explicitly states: add `: never` return type to the function declaration. This is a single-line annotation change per function. Even if multiple helpers need updating, each fix is independently a one-liner with no cascading refactor required.
Closest to 'minimal commitment' (b1). The never return type is a localised annotation on individual functions that always throw or exit. It imposes no structural obligation on callers, no cross-cutting concern, and no architectural shape. Future maintainers are unaffected unless they modify the annotated function itself. The applies_to contexts (web, cli, queue-worker) are broad but the concept itself is a narrow type annotation.
Closest to 'notable trap' (t5). The misconception field explicitly identifies the canonical trap: developers conflate void and never, assuming void covers 'no useful return value' including throws/exits. The distinction — void returns (without a value) vs. never doesn't return at all — is documented and widely taught but still routinely confused by competent PHP developers moving from older versions. The common_mistakes confirm this is a well-known gotcha rather than a catastrophic or exotic surprise.
Also Known As
TL;DR
Explanation
The never return type (PHP 8.1) tells PHP and static analysers that a function will never reach its closing brace — it always throws, calls exit(), or enters an infinite loop. This enables static analysis tools to treat code after a call to such a function as unreachable, tightening type inference. Common uses: redirectAndExit(), throwNotFound(), and abort() helpers. Declaring a function as never that can actually return causes a TypeError at runtime.
Common Misconception
Why It Matters
Common Mistakes
- Using void instead of never for functions that always throw — void means returns without a value, never means doesn't return.
- Declaring never on a function that can sometimes return normally — PHP will throw a TypeError.
- Not declaring never on redirect helpers — analysers think code after the redirect is reachable.
Code Examples
function redirect(string $url) { header('Location: ' . $url); exit; } // return type missing
function redirect(string $url): never { header('Location: ' . $url); exit; }