Sling Academy
Home/PHP/Nullable (Optional) Types in PHP: A practical guide (5 examples)

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

Last updated: February 20, 2024

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.

Next Article: Type Declarations for Class Properties in PHP (5 examples)

Previous Article: Static Return Type in PHP: Explained with examples

Series: Basic PHP Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array
  • PHP: 3 Ways to Get N Random Elements from an Array