Lab 13: PHP Type System

Objective

Master PHP 8's type system: union types (int|string), nullable types (?string), intersection types (Countable&Iterator), never return type, typed properties, mixed, variance (covariance/contravariance), and implementing generic-like patterns with type-safe collections using PHP's type system.

Background

PHP's type system has grown dramatically since PHP 7.0 (scalar type hints) through PHP 8.3 (readonly classes, typed class constants). Unlike Java or TypeScript, PHP types are enforced at runtime, not compile time. This means a mismatch throws a TypeError when the function is called — not when the code is written. Understanding the type system helps you write self-documenting, bug-resistant code that fails loudly at the boundary instead of silently mid-logic.

Time

30 minutes

Prerequisites

  • PHP Foundations Lab 14 (Type System)

  • PHP Practitioner Lab 05 (PHP 8 Features)

Tools

  • Docker: zchencow/innozverse-php:latest


Lab Instructions

Step 1: Union types, nullable, never, typed properties

💡 declare(strict_types=1) only affects the file it appears in. It does NOT affect code called from that file, nor code that calls into that file. It means: when this file calls a function with type hints, PHP will not silently cast types. Without it, function add(int $a) called with "5" will silently cast to 5. With it, the same call throws TypeError. Enable it in every file for predictable behaviour.


Step 2: Intersection types, variance, type-safe collections

📸 Verified Output:


Summary

Type feature
Syntax
PHP version

Union

int|string

8.0

Nullable

?string

7.1

Intersection

A&B

8.1

never

: never

8.1

Typed property

public int $x

7.4

readonly property

public readonly int $x

8.1

strict_types

declare(strict_types=1)

7.0

Further Reading

Last updated