Nullable, Union, Intersection and DNF Types

5.Nullable, Union, Intersection and DNF Types

M

In this chapter

We'll learn how one declaration can allow more than one type: nullable types like ?string, union types like int|float, intersection types like Countable&Traversable, and DNF types that combine both — plus how PHPDoc comments describe types that PHP itself can't express.

13–15 min

The Problem in Real Life

Three functions in the pricing file still have no types. findNote() returns the customer's note — or nothing, if there isn't one. formatPrice() is called with whole pounds from one place and with prices like 12.5 from another.

Mia tries string as the return type of findNote(), and the first booking without a note crashes: Return value must be of type string, null returned. She tries int for formatPrice(), and 12.5 is rejected.

"You don't have to pick one," says Marcus. "A declaration can say this or that. Just be careful you're not saying anything at all."

M

The note is a string or nothing. How do I write "or" in a type?

Mia

One Type vs. a Choice of Types

A value or nothing

Optional values are a string most of the time — and null when they're missing.

Either of two types

Some functions honestly accept an int or a float.

Types PHP can't say

"An array of ints" is a real idea — but PHP's array type can't express it.

Nullable, Union, Intersection and DNF Types

Composite types: a composite type combines several types in one declaration. PHP has four kinds:

  • Nullable: ?string — "a string, or null".
  • Union: int|float — "an int or a float".
  • Intersection: Countable&Traversable — "an object that is both of these".
  • DNF: (Countable&Traversable)|null — intersections and unions together.

Nullable types: put a question mark in front of a type to also allow null: ?string means "a string, or null". It's the right type for anything optional, like findNote()'s return value. For an optional parameter, combine it with a default value: ?string $note = null means the caller may leave it out. (Writing string $note = null without the ? used to make it nullable silently; PHP 8.4 deprecated that, so always write the ?.)

Nullable return and nullable parameter
<?php
declare(strict_types=1);
function findNote(bool $hasNote): ?string
{
return $hasNote ? "Side door, please" : null; // ? : picks one of two (Act 05)
}
var_dump(findNote(true)); // string(17) "Side door, please"
var_dump(findNote(false)); // NULL
function greet(?string $name = null): string
{
return "Hello, " . ($name ?? "guest");
}
echo greet(), "\n"; // Hello, guest
echo greet("Zoë"), "\n"; // Hello, Zoë

Union types: a union type lists several types with | (read it as "or"): int|float accepts an int or a float. Use it when a value honestly can be one of a few types — like a price that's sometimes whole, sometimes not, or a function result that's int|false (chapter 4). ?string is just a short way to write string|null, and you can't mix the two styles: ?int|string is a parse error — write int|string|null. In strict mode, a union is still strict: a string passed to int|float is rejected, as below.

A union type — and it's still strict
<?php
declare(strict_types=1);
function formatPrice(int|float $pounds): string
{
return "£" . $pounds;
}
echo formatPrice(25), "\n"; // £25
echo formatPrice(12.5), "\n"; // £12.5
echo formatPrice("25"); // TypeError: must be of type int|float, string given

Intersection types: an intersection type uses & (read it as "and"): the value must be all of the listed types at once. This only makes sense for objects. Some types describe what an object can do — PHP calls these interfaces (you'll write your own in Act 11). For example, Countable means "can be counted" and Traversable means "can be looped over". A parameter typed Countable&Traversable accepts only objects that can do both. Below, PHP's built-in ArrayObject can, but a plain array isn't an object at all, so it's rejected.

An intersection type
<?php
declare(strict_types=1);
function countItems(Countable&Traversable $items): int
{
return count($items);
}
echo countItems(new ArrayObject(["9:00", "9:30", "11:00"])), "\n"; // 3
echo countItems(["9:00", "9:30"]);
// TypeError: must be of type Countable&Traversable, array given

DNF types: sometimes you need both: "an object that is Countable and Traversable — or null". That's written with brackets: (Countable&Traversable)|null. This combination is called a DNF type (from "disjunctive normal form", a term from logic; you don't need to remember it). The rule: intersections go in brackets, and the brackets are joined with |. You'll rarely write these yourself, but you'll recognise them in libraries.

A DNF type: an intersection, or null
<?php
declare(strict_types=1);
function countOrZero((Countable&Traversable)|null $items): int
{
return $items === null ? 0 : count($items);
}
echo countOrZero(null), "\n"; // 0
echo countOrZero(new ArrayObject([1, 2])), "\n"; // 2

Types PHP can't express — PHPDoc: PHP's own array type only says "some array". It can't say "an array of ints" or "an array with a name key that's a string". For that, developers write types in doc comments (Act 02, chapter 3) using PHPDoc tags like @param and @return. PHP ignores them while running, but editors and PHPStan (Act 21) read and check them. PHPStan even lets you name a complicated type once and reuse it — a type alias, written @phpstan-type. The code below shows both.

PHPDoc types and a PHPStan type alias
<?php
declare(strict_types=1);
/**
* @phpstan-type PriceList array<string, int>
*/
/**
* @param PriceList $pricesPence service name => price in pence
* @return list<string> the names of the services
*/
function serviceNames(array $pricesPence): array
{
return array_keys($pricesPence);
}
print_r(serviceNames(["haircut" => 2500, "beardTrim" => 1000]));

PHP only checks "array". PHPStan also checks that every key is a string and every value an int.

Don't overuse "or": every type you add to a union is one more case the code must handle. int|string|float|bool|null is barely better than mixed. A good rule: a union should have two or three types that the function genuinely handles differently. If you find yourself adding more, convert the value to one type first (chapter 7), then pass it on. The table below sums up the four kinds.

Table — Composite types
KindWrittenAccepts
Nullable?stringA string, or null
Unionint|floatAn int or a float
Union with nullint|string|nullAn int, a string or null
IntersectionCountable&TraversableAn object that is both
DNF(Countable&Traversable)|nullSuch an object, or null
PHPDoc only@param array<string, int> $pricesChecked by PHPStan, not by PHP

Key Takeaway

Composite types let one declaration allow several types: ?T (T or null), A|B (union: either), A&B (intersection: an object that is both) and (A&B)|null (DNF). Unions stay strict under strict_types. For precise types PHP can't express, like "array of ints", use PHPDoc tags such as @param array<int>, which PHPStan checks.

Why This Matters

Composite types let Mia describe real data honestly: notes that may be missing, prices that may have pence, functions that may fail. Every ? in a signature is a reminder to handle the null case — which is exactly the kind of bug that otherwise reaches customers.

And PHPDoc types are how professional PHP teams, BookBay included, describe arrays precisely. When PHPStan joins the project in Act 21, these comments become real checks.

The pricing file is fully typed. Marcus opens one more file, written by a contractor who knew classes well: it's full of types like self, static, parent, object and iterable. "These only make sense with classes," he says, "and you'll write classes in Act 11. But you'll see these names everywhere before then — let's make sure you can read them." That's the next chapter.