Articles/PHP/Type Hinting with Nullable Types in PHP

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.

November 6, 2016·1 min read

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.

PHP
<?php

class Product
{
    private $name;

    public function __construct(?string $name)
    {
        $this->name = $name;
    }

    public function name() : ?string
    {
        return $this->name;
    }
}

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

PHP
<?php

$product = new Product(null);

var_dump($product->name());

The above code would output a response of NULL.