PHP team released their PHP 8.1 version and in this version they add some new features like never return type is one of them. In this tutorial, I will discuss about PHP never
return type. This can be good for you so that I am going to show you what never
the return type is.
In PHP 8.1, never
is a new return type indicates that it will never return
a value, and always throws an exception or terminates with a die
/exit
call.
We know that we can not return something from a method if we declare it as a void
. In other words, a function/method declared never
must not call return
at all, even in the return;
only. Take a look at some examples of PHP never
return type:
function foo(): never {
return;
}
foo()
If we execute this code then it will generate a fatal error like:
Take a look at another example:
function foo(never $a) {}
Using never
as a class property type causes a similar fatal error:
class Foo {
private never $bar;
}
With never
in a Union Type
is not allowed. This is similar to how the void
type is enforced as well.
function foo(): never|string {}
Read also: Don't use if else ladder in php rather use this method
Hope it can help you.
#php