Nullable Types in PHP7: Understanding the Question Marks
PHP7 introduced the concept of nullable types, signified by the question mark (?) before a type declaration (?string, ?int). These types allow for a value to be either the specified type or null.
Parameters
When marking a parameter as nullable, it means that the function can accept either the specified type or null as an argument. For example:
public function (?string $parameter1, string $parameter2) {}
In this case, the function can receive either a string or null for $parameter1, but $parameter2 must be a string.
Return Type
Nullable types can also be used for return values. This indicates that the function can return either the specified type or null. For instance:
function error_func(): int { return null; // Invalid in PHP7.1+ } function valid_func(): ?int { return null; // Valid in PHP7.1+ }
Property Type (PHP7.4 )
PHP7.4 introduced nullable types for property declarations. This allows a property to be either the specified type or null.
Nullable Union Types (PHP8 )
In PHP8, nullable types are shorthand for the union of the specified type and null. For example:
private ?object $bar = null; // PHP7.1+ private object|null $baz = null; // PHP8+
Error Handling
In PHP7.0 and earlier, using the question mark before a type declaration will result in a syntax error. PHP7.1 versions will accept nullable types.
References
The above is the detailed content of How Do Nullable Types Work in PHP7 and Beyond?. For more information, please follow other related articles on the PHP Chinese website!