Union Type in PHP: What It Is and How to Use It
union type allows a variable or function parameter to accept multiple different types, separated by a pipe |. It helps you specify that a value can be one of several types, improving code clarity and type safety.How It Works
Think of a union type like a multi-tool that can perform different jobs depending on the situation. Instead of saying a variable must be only one type, you say it can be one type or another. For example, a variable might accept either an integer or a string.
This is useful because sometimes data can come in different forms, and you want your code to handle all valid options without errors. PHP checks the value against all allowed types and accepts it if it matches any one of them.
Union types were introduced in PHP 8.0 to make type declarations more flexible and expressive, helping developers write clearer and safer code.
Example
This example shows a function that accepts either an int or a float and returns their sum doubled.
<?php function doubleSum(int|float $a, int|float $b): float { return 2 * ($a + $b); } echo doubleSum(3, 4.5); // Outputs 15
When to Use
Use union types when a value can logically be one of several types. For example, a function might accept a string or an integer ID, or a variable might hold either a date string or a DateTime object.
This helps avoid writing extra code to check types manually and makes your intentions clear to anyone reading the code. It also helps tools and editors catch type errors early.
Common real-world cases include handling user input that might be a number or a string, or working with APIs that return different types depending on the situation.
Key Points
- Union types allow multiple types separated by
|. - Introduced in PHP 8.0 for better type safety and flexibility.
- Useful when a value can be one of several valid types.
- Helps reduce manual type checks and improves code clarity.