New never Return Type in PHP 8.1

PHP allows to define type declarations for parameters, return values, and properties. Since PHP 8.1, we can use never return type. It indicates that 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 than void. The void return type indicates that function or class method doesn’t return a value. The never return type guarantees that function or class method throws an exception or terminates 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

Your email address will not be published. Required fields are marked *