Type Hinting with Nullable Types in PHP

As of PHP 7.1, you can now set your type declarations as nullable by simply prefixing them with a question mark ?. In doing so a null value can be passed in as a parameter or returned as a value for your methods.

Let’s look at an example where we setup a simple product class that can pass a name via the constructor. We will type hint the variable to force the use of a string, but we’ll also set it as a nullable type this way a null value can be passed.

Now let’s look at how we would use the above to pass a nullable value to the constructor.

The above code would output a response of NULL.