0
0
PHPprogramming~3 mins

Why Union types in practice in PHP? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how union types can save you from messy type 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 extra code to check the type manually and handle each case separately.

The Problem

This manual checking makes your code longer, harder to read, and easy to forget some cases. It also increases the chance of bugs because you might miss handling a type or mix up the logic.

The Solution

Union types let you declare that a function or variable can accept multiple types directly. This means PHP will automatically check the types for you, making your code cleaner, safer, and easier to understand.

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

It enables writing flexible functions that clearly state what types they accept, reducing bugs and improving code readability.

Real Life Example

For example, a function that formats user input can accept either a string or a number, and union types let you declare this clearly without extra checks.

Key Takeaways

Manual type checks make code long and error-prone.

Union types let you declare multiple accepted types simply.

This leads to cleaner, safer, and easier-to-read code.