Take A Look At PHP 8.1 Never Return Type

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:

output
Fatal error: A never-returning function must not return in ... on line 2

 

Take a look at another example:

function foo(never $a) {}

 

output
Fatal error: never cannot be used as a parameter type in ... on line ...

 

Using never as a class property type causes a similar fatal error:

class Foo {
    private never $bar;
}

 

output
Fatal error: Property Foo::$bar cannot have type never in ... on line 3

 

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 {}

 

output
Fatal error: never can only be used as a standalone type in ... on line 3

 

Read also: Don't use if else ladder in php rather use this method

 

Hope it can help you.

 

#php