Skip to content
Tutorials Center
My learning

Topics

Lesson 110 of 147 ยท Advanced PHP

The PHP Type System in Depth

Master PHP's type system - union, intersection and DNF types, never and static, covariance and contravariance, and generics with @template for PHPStan and Psalm.

PHP started as a loosely typed language, and it still lets you write code without a single type. But since PHP 7 the type system has grown steadily, and by PHP 8.5 it can express almost everything you'd want to say about a value: "an int or a string", "something that is both countable and iterable", "either null or an object that is both A and B", "this function never returns". Types are checked by the engine at run time, and static analysers like PHPStan and Psalm check them, and much more, before your code ever runs.

Type Declarations introduced the basics: scalar types, nullable types, return types and strict_types. This lesson goes deeper. You'll see every kind of type PHP supports and the rules for combining them, the special types never, void, static and mixed, how inheritance interacts with types (covariance and contravariance), and how teams express generics, which PHP itself doesn't have, through PHPDoc annotations.

The building blocks

Every type declaration in PHP is built from these pieces:

Kind Examples Notes
Scalar int, float, string, bool int is accepted where float is expected
Compound array, object, iterable, callable iterable means Traversable|array (since 8.2 literally that union)
Class / interface / enum DateTimeImmutable, Countable, Suit Includes self, parent and static (return only)
Literal-ish null, false, true Standalone since 8.2; true added in 8.2
Special mixed, void, never void and never only as return types

And these are the ways to combine them:

Combination Syntax Since
Nullable ?string (same as string|null) 7.1
Union int|string 8.0
Intersection Countable&Traversable 8.1
DNF (unions of intersections) (Countable&Traversable)|null 8.2

One restriction to remember: callable can't be used as a property type, because whether something is callable can depend on the scope that checks it. Use Closure for properties instead.

Union types

A union type accepts a value of any of its members. It's the honest way to describe a parameter that really does accept several kinds of input, or a function that can return different kinds of results:

PHP Union types and the order of checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Inside the function you narrow the union with checks such as is_int(), is_array() or instanceof; match (true) keeps that tidy. Static analysers understand these checks and know, for example, that $user must be an array in the third arm.

With strict_types=1, a float passed to int|string|array is a TypeError. Without strict types, PHP would try to coerce it to the "best" member using a fixed preference order (int, then float, then string, then bool), which is one more reason to turn strict types on (see Type Juggling and Casting).

PHP rejects redundant unions at compile time: int|int, ?mixed or bool|false are errors, because one member already covers the other. Class types aren't checked for redundancy across inheritance (Exception|Throwable compiles), so keep those tidy yourself.

Intersection and DNF types

An intersection type (PHP 8.1) requires a value to satisfy all its members at once. It only works with class and interface types, since no value is an int and a string at the same time. It's perfect for describing "anything I can both count and loop over":

PHP Intersection and DNF types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

(Countable&Traversable)|array|null is a DNF type (Disjunctive Normal Form, PHP 8.2): a union whose members may be intersections in parentheses. The "normal form" rule means each intersection is grouped on its own, and you can't nest further; A&(B|C) must be written as (A&B)|(A&C).

In practice, intersections appear most often in libraries and tests: a mock object typed as UserRepository&MockObject is both the interface under test and a PHPUnit mock.

Special types: mixed, void, never, null, false, true

mixed (8.0) means "any value, including null". It's equivalent to the union of every type, so it can't be nullable (?mixed is an error). An explicit mixed is still better than no type at all: it tells readers and tools that "anything" is intentional.

void says a function returns nothing. A void function may use return; but not return null;, and its result is always null.

never (8.1) says a function never returns normally: it always throws, calls exit(), or loops forever. That gives analysers precious information: any code after a call to a never function is unreachable, and a variable checked by it is narrowed.

PHP never, void and standalone null, false and true

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

false as a type exists mainly for older APIs that return "a value or false on failure", like strpos(). In new code, prefer ?int (returning null for "nothing") or throw an exception. PHP 8.2 allowed null, false and true as standalone types, which is mostly useful for precise return types in subclasses, as you'll see under variance.

self, parent and static

Inside a class, self means "this class", parent means "the parent class", and static (8.0, return types only) means "the class this method was called on", which can be a subclass. That's the type you want for fluent methods and named constructors that should keep working in subclasses:

PHP self versus static return types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

If where() were declared to return self, the value would still be a PostgresQueryBuilder at run time, but the declared type would say QueryBuilder, and analysers and IDEs would complain that returning() doesn't exist. static keeps the precise type. See Static Properties and Methods for late static binding.

Variance: types and inheritance

When a child class overrides a method, how may it change the types? PHP follows the Liskov substitution principle: a child object must work anywhere the parent works. That leads to two rules (enforced since PHP 7.4):

  • Return types are covariant: a child may return a narrower type. If the parent promises Animal, returning Dog keeps the promise.
  • Parameter types are contravariant: a child may accept a wider type. If the parent accepts Dog, accepting any Animal still handles every call made through the parent.
  • Property types are invariant: they must stay exactly the same, because properties are both read (like a return) and written (like a parameter). PHP 8.4 relaxes this for properties with hooks that are only read or only written.
PHP Covariant returns and contravariant parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The opposite directions are fatal errors at compile time. If DogShelter::adopt() declared object, or admit() required a Puppy, a caller using a Shelter could suddenly get something that isn't an Animal, or pass a Dog that's rejected. PHP refuses with a message like Declaration of DogShelter::admit(Puppy $animal): string must be compatible with Shelter::admit(Dog $dog): string.

Narrowing return types is common and useful: an interface method returning iterable can be implemented to return array, a method returning ?User can return User, and with PHP 8.2's standalone types, a method declared bool in a parent can return false in a child that always fails.

Generics with PHPDoc

PHP has no native generics. You can't declare a Collection<User> that the engine checks. The PHP team has explored it repeatedly, but checking generic types at run time is expensive. Instead, the ecosystem settled on writing generics in PHPDoc annotations, which PHPStan and Psalm (and IDEs like PhpStorm) understand and check statically. PHP itself ignores them.

The core annotation is @template, which declares a type variable for a class or function:

PHP A generic collection with @template

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

At run time, the engine only sees object, so the class adds its own instanceof check. At analysis time, PHPStan reads TypedList<User> and knows that first() returns User|null, that the map() callback receives a User, and that add(new DateTimeImmutable()) is wrong. Running PHPStan on that file would report something like this (read-only, since analysers aren't available in our editor):

TEXT
 ------ ---------------------------------------------------------------------
  Line   type-system.php
 ------ ---------------------------------------------------------------------
  68     Parameter #1 $item of method TypedList<User>::add() expects User,
         DateTimeImmutable given.
 ------ ---------------------------------------------------------------------

The PHPDoc types analysers understand go far beyond PHP's native ones:

PHPDoc type Meaning
list<int> An array with keys 0, 1, 2, ... in order
array<string, User> An array with string keys and User values
array{id: int, name: string, email?: string} An array shape (here email is optional)
non-empty-string, positive-int, int<1, 100> Refined scalars
class-string<T> A class name string such as User::class
callable(int, string): bool A callable with a specific signature
'draft'|'published' Literal values
@template T of Model A type variable restricted to Model and its subclasses
@template-covariant T A type variable that may be narrowed in subtypes (read-only containers)

Generic variance follows the same logic as method variance. An immutable ReadonlyList<Dog> can safely be used as a ReadonlyList<Animal>, so its type variable can be declared @template-covariant. A mutable TypedList<Dog> cannot, because someone could add() a Cat through the Animal view, so a plain @template is invariant.

Native types and PHPDoc types work together. Declare the most precise native type PHP allows (the engine enforces it), then add PHPDoc only where it says more (list<User> instead of array). Don't repeat native types in PHPDoc; tools like PHP-CS-Fixer can remove such redundant tags automatically. The Testing and Coding Standards lessons show how analysers fit into a project.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which declaration is a valid DNF type?

    DNF types are unions of intersections, with each intersection in parentheses. Intersections can't contain unions, can't use the ? shorthand, and only work with class types.
  2. 2. A parent method is declared public function make(): Animal. Which child declaration is allowed?

    Return types are covariant, so a child may narrow Animal to Dog. Widening to object or mixed, or changing to void, breaks callers that expect an Animal.
  3. 3. What happens when a function declared : never reaches its end without throwing?

    A never function must not return. If it would return implicitly, PHP throws a TypeError saying the function must not implicitly return.
  4. 4. Why is static, not self, the better return type for a fluent method in a base class?

    With static, PostgresQueryBuilder::new()->where(...) is known to return PostgresQueryBuilder, so returning() type-checks. With self, tools only know about the base class.
  5. 5. How does PHP treat @template T and @param T $item in a DocBlock?

    PHP has no native generics. Generic annotations live in comments, so only tools that read PHPDoc enforce them.

Summary

  • PHP types combine scalars, compound types, class types and the special types mixed, void, never, null, false and true.
  • Unions (A|B, 8.0) accept any member; intersections (A&B, 8.1, classes only) require all; DNF ((A&B)|null, 8.2) mixes them. Redundant unions are compile errors.
  • never (8.1) marks functions that always throw or exit, which helps analysers narrow types. void functions return null.
  • static return types (8.0) keep fluent and factory methods precise in subclasses.
  • Inheritance follows Liskov: return types are covariant (narrower allowed), parameter types contravariant (wider allowed), property types invariant.
  • Generics live in PHPDoc (@template, list<T>, array{...}, class-string<T>) and are checked by PHPStan and Psalm, not the engine. Declare precise native types first and add PHPDoc only where it adds information.

Next: Performance and OPcache