Nullable types are a powerful feature introduced in PHP 7.1 that allow you to declare variables, parameters, and return values as nullable. This signifies that they can accept or return either the specified type or NULL.
Using a question mark (?) before the type declaration in function parameters indicates that the parameter can be either the specified type or NULL. For example:
public function (?string $parameter1, string $parameter2) {}
In this example, both parameters are nullable. You can pass either a string value or NULL as an argument to the function.
Similarly, a function's return type can be declared as nullable using the question mark syntax. This indicates that the function can return either the specified type or NULL. For example:
function error_func(): int { return null ; // Uncaught TypeError: Return value must be of the type integer } function valid_func(): ?int { return null ; // OK }
Starting with PHP 7.4, you can also declare property types as nullable. This allows for properties to have either the specified type or NULL. For example:
class Foo { private ?object $bar = null; // OK : can be null (nullable type) }
PHP 8.0 introduced a shorthand notation for nullable union types. Writing "?T" is equivalent to "T|null". This allows for more concise type declarations.
class Foo { private object|null $baz = null; // as of PHP 8.0 }
If you try to use the question mark syntax with PHP versions lower than 7.1, you will encounter a syntax error. In such cases, you should remove the question mark.
Nullable types provide a convenient way to handle nullable values in PHP. They allow you to declare that a variable, parameter, or return value can be either a specific type or NULL, making your code more robust and easier to maintain.
The above is the detailed content of How Do Nullable Types Work in PHP, and What Are the Syntax Rules?. For more information, please follow other related articles on the PHP Chinese website!