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