phpreturn-typephp-8.1

What is never return type in PHP 8.1


PHP 8.1 introduces never return type, what is it? and what is the difference between never and void?


Solution

  • 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 vs never

    When to choose 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.