Union types are one of the most exciting new features in PHP 8. Its accepts values of multiple different data types, rather than a single one. Union Types allow a function, method, or property to accept multiple different types for a parameter, return value, or property.
Before PHP 8, you usually had to rely on PHPDoc annotations (comments) or loose typing. Now, you can declare them natively.
Without Union Types
<?php
/**
* @param int|string $id
*/
function findUser($id) {
// $id could be int or string
return "User ID: " . $id;
}
?>
Here, PHPDoc just documents intent — the engine doesn’t enforce it.
Example: With Union Types (PHP 8+)
<?php
function findUser(int|string $id): string {
return "User ID: " . $id;
}
echo findUser(101); // works with int
echo findUser("admin"); // works with string
?>
Now, PHP enforces that $id must be int or string.
Where You Can Use Union Types
- Function & Method Parameters
- Function Return Types
- Class Properties
<?php
class Product {
public function setPrice(int|float $price): void {
$this->price = $price;
}
}
?>
Special Notes
null
can be included:
function logMessage(string|null $msg): void {}
(Or use the shorthand ?string for a nullable type.)
false can be part of a union (common for functions that may return false on failure):
function findIndex(array $list, string $search): int|false {}
Duplicate types aren’t allowed:
// ❌ Invalid
function test(int|int $x) {}
void
cannot be combined with other types.
Benefits of Union Types
Stronger type safety → reduces bugs
Self-documenting code → no more guessing parameter types
Removes reliance on PHPDoc-only annotations
Improves IDE & static analysis support