Never

never は、 関数が戻ってこないことを示す戻り値の型です。 これは、関数の中で exit() がコールされるか、 例外がスローされるか、 無限ループに入るかのいずれかであることを意味します。 よって、この型は union 型 の一部として指定することが出来ません。 PHP 8.1.0 以降で利用できます。

never は、 型理論の用語で言うと、ボトム型にあたります。 つまり、全ての他の型の部分型であり、 継承する際に他の戻り値の型を置き換えることができます。

add a note

User Contributed Notes 2 notes

up
14
ali1289445 at gmail dot com
1 year 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
-5
mateusz dot charytoniuk at protonmail dot com
9 months ago
Overriding the return type of native interfaces:

<?php

class ReadonlyArrayAccess implements ArrayAccess
{
public function
__construct(private readonly $array) {}

public function
offsetExists(mixed $offset): bool
{
return isset(
$this->array[$offset]);
}

public function
offsetGet(mixed $offset): mixed
{
return
$this->array[$offset];
}

public function
offsetSet(mixed $offset, mixed $value): never
{
throw new
LogicException('This array is read only');
}

public function
offsetUnset(mixed $offset): never
{
throw new
LogicException('This array is read only');
}
}
To Top