PHP 8.1 introduces never
return type, what is it? and what is the difference between never
and void
?
never
type declaration introduced to be used as a return type hint for functions that never have return
statement neither implicit nor explicit. And must be terminated by throwing an exception or exiting using exit/die
functions.
function redirect(string $uri): never
{
header('Location: ' . $uri);
exit();
}
Here redirect
is called a never-returning function, because:
1) It has no return
statement defined explicitly.
function redirect(string $uri): never
{
exit();
return 'something';
}
Will prodcue:
PHP Fatal error: A never-returning function must not return
2) It has no return
statement defined implicitly.
function redirect(string $uri): never
{
if (false) {
header('Location: ' . $uri);
exit();
}
}
Since the condition here is never satisfied, the execution jump over the if statement returning an implicit NULL
which will result in:
PHP Fatal error: Uncaught TypeError: redirect(): never-returning function must not implicitly return
3) It ends it's execution with an exit
function
void
can have return;
but never
can't.never
enforces that a function throws or is terminated with exit/die but void
does
not.never
is a sub-type of every other type in PHP’s type system, including void
(this allows return type covariance).void
over never
and vice versa?You should declare a function return type void
when you expect PHP to execute the next statement after the function call. And you should declare it never
when you don't expect PHP to execute the next statement after that function call.