Nullable Type in PHP: What It Is and How to Use It
nullable type allows a variable or parameter to hold either a specific type or null. It is declared by prefixing the type with a question mark, like ?int, meaning the value can be an integer or null.How It Works
Think of a nullable type in PHP like a box that can either hold a specific kind of item or be empty. Normally, if you say a box holds only integers, you can't put anything else inside. But if you make it nullable, it means the box can hold an integer or be empty (null).
In PHP, you declare this by adding a question mark before the type name, for example, ?string. This tells PHP that the variable can be a string or it can be null. This helps avoid errors when a value might not always be set.
Example
This example shows a function that accepts a nullable integer. It prints the number if given, or a message if null.
<?php function printAge(?int $age) { if ($age === null) { echo "Age is not provided.\n"; } else { echo "Age is $age.\n"; } } printAge(25); printAge(null);
When to Use
Use nullable types when a value might be missing or optional. For example, user input fields that can be empty, or database columns that allow null values. Nullable types help your code handle these cases clearly and safely without errors.
This is common in functions that accept optional parameters or when working with data that may not always be set.
Key Points
- Nullable types are declared with a question mark before the type, like
?int. - They allow variables to hold either the specified type or
null. - They help avoid errors when values might be missing or optional.
- Introduced in PHP 7.1 and widely used for safer type declarations.