Advertisement
Intermediate PHP, Type Declarations & Strict Types

What are nullable types and union types in PHP, and how do they let you express that a value could be one of several different possible types?

Short answer

A nullable type, indicated by placing a question mark directly before the type name, means a parameter or return value can either be that specific declared type or explicitly be null, while a union type, indicated using the pipe character between two or more type names, means a…

Save PHP mock interview
Advertisement
AModel answer
A nullable type, indicated by placing a question mark directly before the type name, means a parameter or return value can either be that specific declared type or explicitly be null, while a union type, indicated using the pipe character between two or more type names, means a value can be any one of several explicitly listed types, and both of these features let you accurately express more flexible, real world scenarios where a single rigid type declaration would otherwise be too restrictive to represent what a function actually needs to accept or return.
function findUser(int $id): ?User {
    // returns a User object, or null if not found
}

function formatId(int|string $id): string {
    return (string) $id;
}
Real-world example
A user lookup function declares its return type as a nullable User object, clearly communicating that the function might not find a matching user and could legitimately return null instead of always returning a valid User object.
Likely follow-ups
  • How do you check whether a nullable value is actually null before using it?
  • What is the difference between a union type and simply not declaring any type at all?
Related topics