PHP 8 interview question · Most asked

What are union types in PHP 8 and how do you use them?

Summary

Union types let a parameter, return value or property accept one of several types, written TypeA|TypeB, and are enforced by the engine at runtime.

Longer Answer

Before PHP 8 you could only document "int or string" in a docblock. Union types make that a real contract the engine checks. Any combination of class/interface names and scalar types is allowed, plus null (so ?Foo is shorthand for Foo|null) and the special false pseudo-type (PHP 8.2 also allows standalone true, false and null).

Redundant types are compile-time errors (int|int), and void cannot be part of a union. Under coercive typing mode, PHP tries the types in a defined preference order (int, float, string, bool) when coercing scalars.

Code Example

<?php
declare(strict_types=1);

function formatId(int|string $id): string
{
    return is_int($id) ? sprintf('#%05d', $id) : strtoupper($id);
}

echo formatId(42);      // #00042
echo formatId('ab-1');  // AB-1

Key Points

  • Syntax: int|string, Foo|Bar|null
  • ?T is equivalent to T|null
  • void can never be in a union
  • Prefer narrow unions; a wide union often signals a missing abstraction

Explanation

What interviewers look for

Knowing that unions are runtime-enforced (not just documentation) and that ?T is sugar for T|null.

Common mistakes

  • Using mixed when a two-member union would be more precise
  • Forgetting that false (not bool) is allowed for legacy functions returning T|false

Follow-up questions

  • What are DNF types (PHP 8.2)?
  • How do intersection types differ?

More most-asked PHP 8 questions

← All PHP 8 questions