Using ‘never’ return type in PHP (PHP 8.1+)

Updated: February 20, 2024 By: Guest Contributor Post a comment

Introduction

PHP 8.1 introduced a new return type: never. This feature adds more expressiveness and robustness to PHP’s type system. The never return type indicates that a function or method will not return a value because it will either throw an exception or halt script execution. This concept isn’t new in programming, but its explicit support in PHP is a welcome addition for developers aiming for more precise code documentation and error handling. In this tutorial, we’ll explore how to use the never return type, starting with basics and moving towards more advanced usage.

Understanding never

Before diving into code examples, it’s essential to understand what never means. A function declared with a never return type must not return a value explicitly or reach the end of the function. Typically, it will throw an exception or call a function that exits the script, such as die() or exit(). Let’s explore this concept through examples.

Basic Usage of never

function redirectTo(string $url): never {
  header('Location: ' . $url);
  exit();
}

In the example above, the redirectTo function redirects the user to a given URL. Because the function terminates script execution using exit(), it’s a perfect candidate for the never return type.

Using never to Indicate Exception Throwing

function throwException(): never {
  throw new Exception("This is an exception message.");
}

Here, the function throwException is guaranteed never to return a value because it always throws an exception. Hence, the never return type accurately documents the function’s behavior.

Advanced Usage of never

As you become more familiar with never, you can use it in more complex scenarios. For instance, you might use never in combination with other PHP 8 features such as attributes or unions in function signatures. The following example demonstrates an advanced use case:

#[Attribute]
class MyCustomException extends \Exception {}

function complexFunction(): never|int {
  if(someCondition()) {
    throw new MyCustomException("Custom exception message");
  }
  return 123;
}

In the above example, the function complexFunction uses a union type to indicate that it might either throw an exception (hence the never part of the union) or return an integer. Using never in such a way provides clear documentation about the function’s possible outcomes and enhances code reliability.

Conclusion

The introduction of the never return type in PHP 8.1 enhances the language’s expressiveness and robustness. Through its explicit indication of functions that don’t return, developers can write more accurate and reliable code. Whether for simple redirect functions, error handling through exceptions, or more complex situations involving union types, the never return type is a powerful tool in your PHP arsenal.