Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Nullable types in PHP 7.1

Today, while reading through the code of laravel-vouchers package, I stumbled upon this litle code which looks like this.

/**
 * @param string $prefix
 */
public function setPrefix(?string $prefix): void
{
    $this->prefix = $prefix;
}

Noticed ?string type-hint in the function parameter? This is the thing that had got me. I wondered what this means and why it is useful. So, I needed to find it out. And after a little Googling, I found that these are called as Nullable types which are added in PHP 7.1.

What are Nullable types?

Nullable type simply means when you prepends ? to the type name while declaring types in the method parameters or for return values, it will be marked as nullable. This signifies that as well as the specified type, NULL can be passed as an argument, or returned as a value, respectively.

So, if you type hint parameter with ? like below

function printMe(?string $name)
{
    var_dump($name);
}

printMe('FooBar'); // string(10) "FooBar"
printMe(null); // NULL

As you can see, the method will accept both string and null as a parameter without any error and process them likewise. But if you don’t pass any arguments it then it will result into a fatal error.

Similarly, if you type hint return type of a method with ? like below

function testReturn(): ?string
{
    return 'FooBar';
}

var_dump(testReturn()); // FooBar

function testReturn(): ?string
{
    return null;
}

var_dump(testReturn()); // NULL
Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?