The “never” Return Type for PHP
It’s not a big addition, but it’s a welcome one
Wow, the PHP train doesn’t stop, does it? There was one RFC (Request for Comments) for a new capability of the PHP language itself that closed voting just recently, and it’s called never
.
PHP 8.1 is planned for the end of the year, and in addition to Fibers, the new never
keyword will allow you to mark a function as “never” returning. The function will stop the normal script execution by either throwing an exception, looping forever, or simply telling PHP to stop with die()
.
Using the New “never”
The best way to show why the never
return type should make sense is with a simple example about returning types in functions. Don’t think about the example too much. It is just for illustration.
Let’s say we have a class, Credentials
, that users can extend to use in their project. This class saves sensible data and makes it available for other classes, like an HTTP client that connects to different external APIs.
If we’re extending it to include sensible data, we can avoid leaking it by accident. To do that, we could easily put an exception in the __toString()
method to stop the leak in its tracks:
The return type doesn’t make much sense here. Not only are we not returning a string
, but it will never return anything! We have always had to document it somewhere, as PHP would never be aware of this break in the code.
Thanks to the new RFC, we can “override” it thanks to the return covariance, making it clear at the code level: This function will never return anything— hence the name of the new keyword.
public function swim(): never
{
throw new RuntimeError("Cats are very bad swimmers!")
}
You may say that void
is the same, but it’s not. When you use void
, you mean the function returns nothingness, so the script can still continue normal execution, while never
does not.
You should use never
for functions that, well, never return anything (e.g. when they loop forever):
What Does This Mean for My App?
Well, if you’re using a function that only throws an exception for pure convenience or it stops the script execution, you can use never
once PHP 8.1 lands in your server. It’s difficult to see endless loops in the wild, but if you do, you may also use never
.
One of the cool things is that PHP will panic if a function that never returns actually returns something else, based on the pull request over at PHP.
function thisWillError(): never
{
return 'oops!';
}
If you use static analysis code tools, you may catch an error if you pass through a function that never returns and expect normal execution, as it will be easier to catch and fix it.