In PHP, as in many other programming languages, null is a special type that represents the absence of a value or a reference to a non-existent value. However, the way null interacts with other types in PHP can be a source of confusion, especially when it comes to typing.

Nullable Types and the ? Operator

Starting from PHP 7.1, PHP supports nullable types using the ? operator which can be placed in front of a type name. This indicates that the value can be of that type or null.

For instance, ?string means that the value can be a string or null. This can be quite useful when you want to allow a function to accept or return a null value in addition to a value of a certain type.

function hello(?string $name): ?string {
    if ($name === null) {
        return null;
    }
    return "Hello, " . $name;
}

In this function, both the $name argument and the return value can be a string or null.

Null Behavior in PHP 8.1

Prior to PHP 8.0, if a function parameter had a declared type (like string) and a default value of null, PHP would throw an error. This is because null is not a string, so it does not match the declared type.

// Prior to PHP 8.0, this would cause an error
function hello(string $name = null) {
    return "Hello, " . $name;
}

However, starting from PHP 8.0 , PHP allows a parameter with a declared type to have a default value of null, even if null does not match the declared type. This means that the above code is now valid in PHP 8.0 and above. If you call hello() without arguments, $name will be null and the function will work without issues.

Which one should you use?

So, should you use ?string or string = null? It depends on what you want to do.

If you want a value to be able to be explicitly passed as null, you should use ?string. This allows null to be passed as an argument to the function.

hello(null); // Valid

On the other hand, if you want a value to always be a string when it is provided, but that it can be omitted (in which case it will be null), you should use string = null.

hello(null); // Error
hello();     // Valid, $name will be null

In summary, mastering the intricacies of PHP, like the nullable types and the nuanced behavior of null, can significantly enhance your programming skills. While it may seem like a small detail, understanding these concepts can contribute to cleaner, more efficient, and error-free code. So, stay curious and never stop delving deeper into the language!