Missing in PHP7: Nullable return types

This is the fifth post in my Missing in PHP7 series. The previous one is about Collections. This is a short post, as there really is not much to explain or motivate.

Nullable return types

As of PHP7, we have return types at our disposal. Unfortunately, these have some annoying limits. One of them I described in my PHP Collections blog post. Another is the lack of nullable return types. This blog post is about the latter.

Take the following code

This is a repository, that obtains a kitten from the persistence in some manner (such as using Doctine ORM). It then returns the kitten as an Entity part of the domain, in this case represented by the Kitten class. As you can see, we’re using a return type hint for the getKittenFromOrmObject private method. However for the public method, we’re prevented from using a return type hint, as it can also return null. This is really unfortunate, as we need to fall back to using documentation instead of code. The IDE I’m currently using, PhpStrom, manages to add salt to the wound by then requiring all parameters to also be present in the docblock if you don’t want to get any warnings about them not being there.

It’d be very nice to be able to do

Or alternatively

After asking about this on Stack Overflow several months ago, I found out that there is an RFC for nullable return type declarations. Unfortunately this appears to not be going anywhere for now. A somewhat related RFC, one for introducing a void return type, has on the other hand already been implemented and will land in PHP 7.1.

Nullability in Java

I have not often worked with Java in the recent past, though when I did, I always ended up being surprised by it’s default nullability of types.

The caller of someStuff can pass in null, which forces null checks in many places, be it like above, or in the form of a guard clause that throw a type error. This is annoying, and indeed, the Clean Code book even has a chapter on avoiding returning null.

So not all is bad in PHP-land when it comes to nullability 🙂

2 thoughts on “Missing in PHP7: Nullable return types”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.