Skip to main content

How to Allow null in a PHP Type with a Question Mark (?)

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

A question mark in front of a type in PHP, as in ?string, lets a parameter, a return value or a property hold null as well as a value of that type. Without it, passing null to a typed parameter stops the script with a TypeError.

Syntax​

Syntax
function <name>(?<type> $<parameter>)
function <name>(): ?<type>
PartWhat it does
?Allows null as well as <type>.
<type>One type, such as string, int or the name of a class.
$<parameter>A parameter that accepts a <type> value or null.
: ?<type>A return type: the function may return a <type> value or null.

The PHP manual: "A single base type declaration can be marked nullable by prefixing the type with a question mark (?). Thus ?T and T|null are identical."

The Example​

The example's greeting function takes a nickname that may be missing: a string, or null. It greets Ada by her nickname, and someone without a nickname with a plain hello. Then the ? comes out of the type, and the same call with null fails.

Prerequisites​

  • PHP. This guide uses PHP 8.6.0.

Step 1: Write the Code​

Create a file named main.php:

main.php, which declares a greeting function with a ?string parameter that returns Hello! when the nickname is null and a greeting with the nickname otherwise, then echoes greeting for Ada and for null.

main.php
<?php

declare(strict_types=1);

// ?string accepts a string or null.
function greeting(?string $nickname): string
{
if ($nickname === null) {
return 'Hello!';
}
return "Hello, {$nickname}!";
}

echo greeting('Ada') . "\n";
echo greeting(null) . "\n";

declare(strict_types=1); makes PHP check argument types strictly instead of converting values. {$nickname} inside double quotes puts the value of $nickname into the string.

Step 2: Run It​

Terminal
php main.php
Output
Hello, Ada!
Hello!

The command is the same in zsh, bash and PowerShell.

Step 3: Take Out the Question Mark​

Replace main.php with a version whose parameter is string, without the ?:

main.php
<?php

declare(strict_types=1);

// string, without the ?, accepts only a string.
function greeting(string $nickname): string
{
return "Hello, {$nickname}!";
}

echo greeting(null) . "\n";
Terminal
php main.php
Output
PHP Fatal error: Uncaught TypeError: greeting(): Argument #1 ($nickname) must be of type string, null given, called in /Users/Shared/you/main.php on line 11 and defined in /Users/Shared/you/main.php:6
Stack trace:
#0 /Users/Shared/you/main.php(11): greeting(NULL)
#1 {main}
thrown in /Users/Shared/you/main.php on line 6

Fatal error: Uncaught TypeError: greeting(): Argument #1 ($nickname) must be of type string, null given, called in /Users/Shared/you/main.php on line 11 and defined in /Users/Shared/you/main.php:6
Stack trace:
#0 /Users/Shared/you/main.php(11): greeting(NULL)
#1 {main}
thrown in /Users/Shared/you/main.php on line 6

A zsh terminal where php main.php prints Hello, Ada! and Hello!; for the changed file it stops with PHP Fatal error: Uncaught TypeError: greeting(): Argument #1 ($nickname) must be of type string, null given, shown twice.

What Happened​

  • greeting('Ada') returned Hello, Ada!, because a string fits ?string.
  • greeting(null) returned Hello!. ?string let null in, and the if handled it before the string was built.
  • Without the ?, the call with null stopped the script with TypeError: greeting(): Argument #1 ($nickname) must be of type string, null given. The message names the function and the argument, and both places: where it was called, line 11, and where the function is defined, line 6. Nothing caught the error, so PHP stopped.
  • The error appears twice because this PHP's settings both log errors to the terminal, as PHP Fatal error:, and display them, as Fatal error:.

strict_types isn't what refused null. In a separate check without declare(strict_types=1), the same call failed with the same TypeError.

Common Mistakes​

MistakeWhat happensDo this instead
Writing string $nickname = null to allow nullPHP 8.6 prints Deprecated: greeting(): Implicitly marking parameter $nickname as nullable is deprecated, the explicit nullable type must be used insteadWrite ?string $nickname = null
Expecting ?string to make the argument optionalCalling greeting() with no argument fails with ArgumentCountError: Too few arguments to function greeting(), 0 passed … and exactly 1 expectedAdd a default: ?string $nickname = null
Returning null from a function declared : stringTypeError: nick(): Return value must be of type string, null returnedDeclare the return type as ?string
Writing ?mixedFatal error: Type mixed cannot be marked as nullable since mixed already includes nullWrite mixed, which already allows null

Troubleshooting​

SymptomLikely causeFix
TypeError: greeting(): Argument #1 ($nickname) must be of type string, null givennull reached a parameter whose type doesn't allow itAdd ? to the type, or don't pass null
Deprecated: ... Implicitly marking parameter $nickname as nullable is deprecatedA typed parameter has = null as its default, without ?Add ? to the type
Parse error: syntax error, unexpected token "|", expecting variable? in front of a type with |, such as ?int|stringWrite int|string|null

FAQ​

Is ?string the same as string|null?​

Yes. The manual says "?T and T|null are identical", and when I asked PHP's ReflectionFunction for the parameter types of two functions, one with ?string and one with string|null, both printed as ?string.

Can I use ? with several types?​

No. ? works with a single type: ?int|string failed with Parse error: syntax error, unexpected token "|", expecting variable. For several types, add null to the list: int|string|null.

Does ? work on properties too?​

Yes. In my check, a class property declared public ?string $nickname = null; held null and then "Addie", while assigning null to a property declared public string $name failed with TypeError: Cannot assign null to property User::$name of type string.

Conclusion​

?type lets a parameter, a return value or a property hold null as well as a value of that type. Use it where "no value" is a real case and check for null before using the value. Leave the ? out where null would be a mistake, so PHP stops the call for you.

Additional Resources​