PHP return type ‘never’

PHP 8.1 introduces a new return type called ‘never’ that explicitely says that a method will never return a value. Similar to returning void, however after returning never you should guarantee that the program will either throw an exception or terminate itself with exit or die. If you fail to enforce the termination PHP will fail with TypeError exception. Let’s look at a few examples:

In the past we could have similar redirect method:

public function redirectToUrl(string $url): never
{
    header('Location: ' . $url);
}

echo 'You should never see this. As you used never return type and failed to terminate the program with exit PHP will complain with TypeError Exception';

You should never see this. As you used never return type and failed to terminate the program with exit/die PHP will complain with TypeError exception.

public function redirectToUrl(string $url): void
{
    header('Location: ' . $url);
    exit();
}

Leave a Reply

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