0
0
PHPprogramming~3 mins

Why Union types in PHP? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your code could accept different types without messy checks and bugs?

The Scenario

Imagine you are writing a function that can accept either a number or a string. Without union types, you have to write separate functions or add lots of checks everywhere to handle each type manually.

The Problem

This manual approach is slow and error-prone because you must constantly check the type and write duplicate code. It's easy to forget a case or make mistakes, leading to bugs and confusing code.

The Solution

Union types let you declare that a function or variable can accept multiple types directly. This makes your code clearer, safer, and easier to maintain because the language itself knows what types are allowed.

Before vs After
Before
function process($value) {
  if (is_int($value)) {
    // handle int
  } elseif (is_string($value)) {
    // handle string
  } else {
    throw new Exception('Invalid type');
  }
}
After
function process(int|string $value) {
  // handle int or string directly
}
What It Enables

Union types enable writing flexible and robust code that clearly communicates what types are accepted, reducing bugs and improving readability.

Real Life Example

For example, a function that formats user input might accept either a string or an integer ID. Union types let you declare this clearly so the function works smoothly with both.

Key Takeaways

Manual type checks are slow and error-prone.

Union types let you accept multiple types cleanly.

This leads to clearer, safer, and easier-to-maintain code.