In PHP 7, a new feature known as "nullable types" was introduced. It allows developers to specify that a parameter or return value can be either the specified type or null. Nullable types are denoted by a question mark (?) placed before the type declaration.
Syntax:
function test(?string $parameter1, string $parameter2) {}
test("foo", "bar"); // OK test(null, "foo"); // OK test("foo", null); // Error
Syntax:
function error_func(): int { return null ; // Error: Return value must be of type integer } function valid_func(): ?int { return null ; // OK }
Syntax:
class Foo { private ?object $bar = null; // OK: can be null }
As of PHP 8.0, "?T notation is considered a shorthand for the common case of T|null".
Syntax:
class Foo { private object|null $baz = null; }
If the PHP version used is lower than 7.1, a syntax error will be thrown if nullable types are used. In such cases, remove the question mark (?).
The above is the detailed content of How Do Nullable Types Work in PHP 7 and Above?. For more information, please follow other related articles on the PHP Chinese website!