Union Types in PHP: A practical guide (5 examples)

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

Introduction

In PHP, the concept of types is crucial for ensuring that variables and returns from functions behave as expected. PHP 8 introduced a remarkable feature that broadened the horizons for type declarations: Union Types. Union Types allow a variable or return value to be of one type or another, offering flexibility and robustness in type declarations. This tutorial will provide a comprehensive overview of Union Types in PHP through 5 practical examples, ranging from basic to advanced applications.

What areUnion Types?

Before PHP 8, variables, parameters, and return types could be assigned a single type. PHP 8’s introduction of Union Types changed this by allowing the assignment of two or more types to these elements, enhancing type safety and reducing the need for type juggling. This feature is particularly useful in scenarios where a function might return different types of data or accept multiple types as arguments.

Example 1: Basic Union Type Declaration

// Declaring a function with Union Type
function getMixedValue(int|string $value): int|string {
   return $value;
}

// Output
echo getMixedValue(10); // 10
echo getMixedValue('Hello'); // Hello

This example demonstrates the basic form of using Union Types, allowing the function to accept or return an integer or a string.

Example 2: Union Types with Objects

// Using Union Types with object classes
class Product {
    public function __construct(public string $name) {}
}
class User {
    public function __construct(public string $username){}
}

function getUserOrProduct(string $type): Product|User {
    if ($type == 'product') {
        return new Product("Laptop");
    } else {
        return new User("john_doe");
    }
}

// Output
var_dump(getUserOrProduct('product'));
var_dump(getUserOrProduct('user'));

This example showcases how Union Types can be used with object classes, allowing a function to return instances of different classes.

Example 3: Union Types in Class Properties

// Using Union Types for class properties
class Order {
    public int|string $orderId;
    public function __construct(int|string $orderId) {
        $this->orderId = $orderId;
    }
}

// Output
$order = new Order(101);
echo $order->orderId; // 101
$order = new Order('ORD-202');
echo $order->orderId; // 'ORD-202'

Using Union Types in class properties enables more flexible instance properties that can contain different types.

Example 4: Advanced Union Type Usage

// Advanced usage of Union Types
function processData(array|int|string $data): void {
    if (is_array($data)) {
        echo "Array received";
    } elseif (is_int($data)) {
        echo "Integer received";
    } elseif (is_string($data)) {
        echo "String received";
    }
}

// Output
processData([1,2,3]); // Array received
processData(42); // Integer received
processData("Hello World"); // String received

In this advanced example, Union Types are leveraged to create flexible function parameters that can handle multiple types of input, enhancing the function’s usability across different data scenarios.

Example 5: Nullables and Union Types

// Combining nullable types with Union Types
function getNullableValue(int|string|null $value): int|string|null {
    return $value;
}

// Output
var_dump(getNullableValue(null)); // null
var_dump(getNullableValue(45)); // int(45)
var_dump(getNullableValue("PHP 8")); // string("PHP 8")

This example illustrates how Union Types can be combined with nullable types, offering even more flexibility for functions that may return null under certain conditions.

Conclusion

Union Types in PHP provide a powerful tool for developing more flexible and expressive code. By allowing variables, properties, and return values to be of more than one type, developers can create more versatile functions and classes. The examples presented in this guide showcase the diverse applications of Union Types, from simple to complex scenarios, demonstrating their potential to streamline and improve PHP applications.