Join my Laravel for REST API's course on Udemy 👀

PHP: 'never' return type

June 3, 2022  ‐ 1 min read

With PHP 8.1 the never return type was introduced. At a first glance the existence of this kind of return type seems somewhat what. What is the use of functions that never return something?

You use the never type to indicate that your function either:

  • never terminates, think of an indented infinite loop for example.
  • terminates with an exception.
  • quits the program using the exit() function.

The first option is shortly demonstrated in the snippet below. Where the program never terminates on its own.

<?php

function main(): never {
  while (true) {
    sleep(1);
    echo "Fetching data...\n";
  }
}

main();

For a reference in the documentation you may follow this link.