PHP 8.1 – Extra return type :noreturn

PHP 8.1 – Extra return type :noreturn

no return sign

For any methods or function which are meant to always throw exception or exit the code using things like: exit() or die() a new return type of: noreturn was added. The sample usage could be: function iWillAlwaysExit(): noreturn .

Redirect functions that always call exit (either explicitly or implicitly) are good candidates for such a return type:

function redirect(string $uri): noreturn {
    header('Location: ' . $uri);
    exit();
}
 
function redirectToLoginPage(): noreturn {
    redirect('/login');
}

Like void, the noreturn type is only valid when used as a function return type. Using noreturn as an argument or property type produces a compile-time error:

class A {
    public noreturn $x; // Fatal error
}

More about PHP 8.1

Read about all PHP 8.1 features and changes in here.

Leave a Comment