Never

never — тип, который разрешается указывать только как возвращаемое значение, которое указывает, что функция прекратит работу без возврата значения. Функция либо вызывает конструкцию языка exit(), либо выбрасывает исключение, либо это бесконечный цикл. Поэтому этот тип нельзя объявлять в объединении типов. Тип доступен с PHP 8.1.0.

На языке теории типов, never — нижний тип. Это означает, что он — подтип остальных типов и заменяет другие возвращаемые типы при наследовании.

Добавить

Примечания пользователей 3 notes

up
29
ali1289445 at gmail dot com
3 years ago
<?php

function sayHello(string $name): never
{
    echo "Hello, $name";
    exit(); // if we comment this line, php throws fatal error
}

sayHello("John"); // result: "Hello, John"
up
4
dcfynn at icloud dot com
1 year ago
I think the description should be corrected from return-only to non-return function since the context is now misleading
up
0
harl at gmail dot com
1 day ago
Never cannot be used in a union type because, being the bottom type, it is already automatically a subtype of every other type. "A|never" is equivalent to "A".

When one type is "obviously" a subtype of another (i.e., it doesn't require loading the class definitions of all the types involved), the former is redundant in union types, and PHP flags the union of both as an error.

Similarly for intersection types, where "A&never" means the same thing as "never". It "obviously" doesn't make sense to mention A there, so PHP won't allow doing so.
To Top