phpday 2027 - Call for Papers

Never

never é um tipo de retorno que indica que a função não termina. Isso significa que a função chama exit(), lança uma exceção ou é um loop infinito. Portanto, não pode fazer parte de uma declaração de tipo de união. Disponível a partir do PHP 8.1.0.

Uma instrução return em uma função never é um erro de compilação, mesmo que o return não fosse alcançado durante a execução. Se o fluxo de execução chegar ao fim de uma função never sem sair, lançar uma exceção ou entrar em um loop infinito, será lançado um TypeError.

never é, na linguagem da teoria dos tipos, o tipo inferior. Isso significa que é o subtipo de todos os outros tipos e pode substituir qualquer outro tipo de retorno durante a herança.

Notas de Usuários 3 notes

up
37
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
3
dcfynn at icloud dot com
2 years ago
I think the description should be corrected from return-only to non-return function since the context is now misleading
up
-3
harl at gmail dot com
9 months 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.
Adding new notes is disabled. Please see the links in the Found A Problem? section.
To Top