<?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 is a return-only type indicating the function does not terminate. This means that it either calls exit(), throws an exception, or is an infinite loop. Therefore, it cannot be part of a union type declaration. Available as of PHP 8.1.0.
never is, in type theory parlance, the bottom type. Meaning it is the subtype of every other type and can replace any other return type during inheritance.
<?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');
}
}