Frank Perez

Frank Perez

Keep in touch

An experienced Web Developer with years of experience in design, programming and server administration.

Blog

Overview

© 2024 by Frank Perez.

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.

<?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

$product = new Product(null);

var_dump($product->name());

The above code would output a response of NULL.