Understanding Union Types in PHP
This article explains what union types are in PHP and demonstrates how to declare them in your code. Introduced in PHP 8.0, union types allow you to specify that a value can belong to one of several different types, moving type verification from informal documentation to enforced runtime checks.
What Are Union Types?
A union type is a type-hinting feature that allows a variable, parameter, property, or return value to accept more than one specific type.
Before PHP 8.0, if a function parameter could accept either an integer or a float, developers had to rely on PHPDoc annotations to document this behavior, or omit type hints entirely. With union types, these multiple type possibilities are formally declared directly in the PHP code, allowing the PHP engine to enforce type safety at runtime.
How to Declare Union Types
Union types are declared by combining two or more types separated by
a vertical bar or pipe symbol (|).
Here are the primary ways to use union types in PHP:
1. Function and Method Parameters
You can specify that a function accepts multiple types of input.
function displayValue(int|float|string $value): void {
echo "The value is: " . $value;
}
displayValue(42); // Works
displayValue(3.14); // Works
displayValue("Hello"); // Works2. Return Types
You can define a method or function to return one of several types.
function calculateDiscount(double $price): int|float {
if ($price > 100) {
return $price * 0.2; // Returns a float
}
return 0; // Returns an integer
}3. Class Properties
Union types can also be applied to typed class properties.
class Product {
public string|int|null $id;
public function __construct(string|int|null $id) {
$this->id = $id;
}
}Key Rules and Limitations
When using union types in PHP, there are several syntactical rules you must follow:
- The
nullType: If a type can be null, you must explicitly includenullin the union (e.g.,string|int|null). You cannot combine the nullable shorthand (?) with union types (e.g.,?string|intis invalid). - The
voidReturn Type: Thevoidtype represents the absence of a return value. Because of this, it cannot be combined with any other type in a union (e.g.,string|voidis invalid). - Duplicate and Redundant Types: You cannot list
duplicate types (e.g.,
int|int). PHP also prevents redundant types that overlap, such asbool|falseorobject|ClassName, which will trigger a compile-time error. - The
mixedType: Themixedtype inherently represents all possible types. Therefore, combiningmixedwith any other type (e.g.,mixed|int) is redundant and not allowed.