Skip to content
Advertisement

Nullable return types in PHP7

PHP 7 introduces return type declarations. Which means I can now indicate the return value is a certain class, interface, array, callable or one of the newly hintable scalar types, as is possible for function parameters.

JavaScript

Often it happens that a value is not always present, and that you might return either something of some type, or null. While you can make parameters nullable by setting their default to null (DateTime $time = null), there does not appear to be a way to do this for return types. Is that indeed the case, or am I somehow not finding how to do it? These do not work:

JavaScript

Advertisement

Answer

PHP 7.1 Now supports nullable return types. The first RFC I linked to is the one they went for:

JavaScript

old answer:

Since my comment was actually an answer to the question:

PHP 7 won’t support nullable return-types just yet, but there’s an RFC out to address just that, it aims to land in PHP 7.1. If it passes, the syntax would then affect all type-hints (both return types and type-hints):

JavaScript

There’s also a competing RFC to add union types, which would be able to do the same thing, but would look different:

JavaScript

For now, though, you’ll have to write:

JavaScript

Or just return an empty string to be consistent with the return type, and check falsy value:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement