0
0
PhpConceptBeginner · 3 min read

Nullable Type in PHP: What It Is and How to Use It

In PHP, a 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
<?php
function printAge(?int $age) {
    if ($age === null) {
        echo "Age is not provided.\n";
    } else {
        echo "Age is $age.\n";
    }
}

printAge(25);
printAge(null);
Output
Age is 25. Age is not provided.
🎯

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.

Key Takeaways

Nullable types let variables hold a type or null using a question mark prefix.
They make handling optional or missing values safer and clearer in PHP code.
Use nullable types for optional parameters or data that can be empty.
Nullable types were introduced in PHP 7.1 and improve type safety.