Nullable (Optional) Types in PHP: A practical guide (5 examples)

Updated: February 20, 2024 By: Guest Contributor Post a comment

Overview

In the evolving landscape of web development, PHP has remained a cornerstone for backend technologies. As applications grow in complexity, handling the absence of values or the concept of ‘null’ becomes increasingly important. PHP 7.1 introduced nullable types, which offer an elegant solution for this. This article explores the practicality of nullable types in PHP through five illustrative examples, progressing from basic to more advanced use cases.

Understanding Nullable Types

Before diving into examples, let’s understand what nullable types are. In PHP, a variable can explicitly be set to null to represent the absence of a value. However, before PHP 7.1, type declarations in functions or methods could not accept null unless explicitly doing so. With nullable types, you can prefix the type declaration with a question mark ?, indicating that a parameter can either be of a specified type or null.

Example 1: Basic Nullable Type Declaration

function getUserName(?string $name): ?string {
    return $name;
}

// Calling with a string
echo getUserName("John"); // Outputs: John

// Calling with null
echo getUserName(null); // Outputs nothing

This simple function demonstrates how a parameter and return type can explicitly accept both a specified type and null.

Example 2: Nullable Types in Class Properties

With PHP 7.4, property type declarations were introduced, allowing properties to be nullable as well. Here’s how to use nullable types in class properties:

class User {
    public ?string $name = null;
}

$user = new User();
$user->name = "Alice";
// Or set to null
$user->name = null;

This enables more robust type declarations for class properties, promoting cleaner and more predictable code.

Example 3: Combining Nullable Types with Default Null Values

Parameter declarations can be combined with default null values to further ease handling optional parameters:

function setLanguage(?string $lang = null) {
    echo "Language: " . ($lang ?? "Not specified");
}

setLanguage("PHP"); // Outputs: Language: PHP
setLanguage(); // Outputs: Language: Not specified

This pattern is very convenient for functions that can optionally accept parameters without compromising type security.

Example 4: Nullable Return Types and Error Handling

Nullable return types can be particularly useful in error handling, where a successful operation returns a result and an unsuccessful one returns null. Here is how you might implement this:

function findProduct(int $id): ?array {
    // Simulate searching for a product
    $product = $id === 1 ? ['id' => 1, 'name' => 'Laptop'] : null;
    return $product;
}

$product = findProduct(1);
if ($product !== null) {
    echo "Product found: " . $product['name'];
} else {
    echo "Product not found.";
}

By utilizing nullable return types, functions can express intended outcomes more explicitly, improving code readability and reliability.

Example 5: Advanced Usage with Typed Properties

Building on Example 2, in PHP 7.4 and later, you can combine nullable types with typed properties for more sophisticated scenarios, like dependency injection:

class DatabaseConnection {
    public function __construct(public ?mysqli $connection = null) {}
}

// Create a new instance without a connection
$dbConnection = new DatabaseConnection();

// Later inject the mysqli connection
$dbConnection->connection = new mysqli("localhost", "user", "pass", "database_name");

In this pattern, a class property can explicitly signal when a dependency is optional, making the codebase more flexible and semantically clear.

Conclusion

Nullable types in PHP greatly enhance the language’s type system, making code more expressive and bugs less frequent. By leveraging nullable types, developers can write more reliable, readable, and manageable code. As PHP continues to evolve, understanding and implementing these aspects become indispensable for modern PHP development.