New never Return Type in PHP 8.1

New never Return Type in PHP 8.1

PHP allows defining type declarations for parameters, return values, and properties. Since PHP 8.1, we can use never return type. It indicates that a function or class method throws an exception or terminates execution of the script by calling die or exit.

<?php

function redirectToPage(string $url): never
{
    header('Location: '.$url);
    exit;
}

The never return type is different from void. The void return type indicates that a function or class method doesn't return a value. The never return type guarantees that a function or class method throws an exception or terminates the script. If it doesn't, PHP produces a fatal error:

<?php

function saySomething(string $message): never
{
    echo $message;
}

saySomething('Hello');
Fatal error: Uncaught TypeError: saySomething(): never-returning function must not implicitly return in ...

There are some important notes:

  • The never type is only allowed to use as return type. It cannot be used to define type for parameters and properties.
  • A function or class method which declared with never return type cannot call return statement, and not even return; that doesn't specify return value.
  • The never type cannot be used as part of the union types. For example, string|never is not allowed and cannot be used to define return type.

Leave a Comment

Cancel reply

Your email address will not be published.