<?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 ist ein reiner Rückgabetyp, der anzeigt, dass die Funktion nicht beendet wird. Das bedeutet, dass sie entweder exit() aufruft, eine Ausnahme wirft oder eine Endlosschleife ist. Daher kann er nicht Teil einer Union-Typ-Deklaration sein. Verfügbar seit PHP 8.1.0.
Im Sprachgebrauch der Typentheorie ist never der unterste Typ. Das bedeutet, dass er der Untertyp jedes anderen Typs ist und bei der Vererbung jeden anderen Rückgabetyp ersetzen kann.
<?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');
}
}