<?php
function sayHello(string $name): never
{
echo "Hello, $name";
exit(); // if we comment this line, php throws fatal error
}
sayHello("John"); // result: "Hello, John"
never 是仅用于返回的类型,表示函数不会终止。这意味着它要么调用 exit(),要么抛出异常,要么无限循环。因此,它不能是联合类型声明的一部分。自 PHP 8.1.0 起可用。
never 是类型理论中的最底层类型。这意味着它是其它所有类型的子类型,并在可以在继承期间替换其它任何返回类型。
<?php
function sayHello(string $name): never
{
echo "Hello, $name";
exit(); // if we comment this line, php throws fatal error
}
sayHello("John"); // result: "Hello, John"
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');
}
}