Nullability support

Posted on by Anton Monakov

PHP 7.1 introduced support for nullable types. When declaring a parameter or a return value, you can prepend its type with “?” to explicitly state that it is nullable. This way, you permit the NULL value to be passed or returned, besides the actual specified type.

PhpStorm has been supporting nullable types for some time now, and with version 2017.3, their support is enhanced even further.

To make use of it, set your project’s PHP Language Level to 7.1 or later. You can either do it manually under Settings | Languages & Frameworks | PHP or let PhpStorm take a look at your code and handle it for you automatically:

Language_level_detection

Having set the language level, you can take advantage of nullable types when performing the Extract Interface refactoring:

extract_interface

As well as the Change Signature refactoring:

change_signature

When creating a class, you can annotate a class field with the /** @myVar null|string $myVar */ PHPDoc block thus marking it as nullable. If you generate a class constructor method at a later point, it will follow the annotation, with the nullable type hint specified:

create_constructor

The same applies to generating the getter and setter methods for your class fields:

create_getter_setter

With nullability support in place, you no longer need omit type declarations in your code or provide the default null value for the function parameter when you don’t want to do so.

Your JetBrains PhpStorm Team
The Drive to Develop

Subscribe

Subscribe for updates