What It Is
The State pattern gives an object different behavior in different states by making each state its own class. The object holds its current state and delegates to it; moving to another state means swapping the object.
It replaces the growing match ($status) { ... } repeated through half the methods with one small class per state.
Example: An Order's Life
An order is new, then paid, then shipped. Each state class answers describe() its own way and knows which state comes next — the order itself contains no status logic at all.
Each state is a class
advance() is one line forever. Adding a "delivered" state is a new class plus one changed next() — no match to hunt through. (The states carry a State suffix because new is a keyword and cannot name a class.)
Output: PHP script
<?php
interface State {
public function next(): State;
public function describe(): string;
}
class NewState implements State {
public function next(): State { return new PaidState(); }
public function describe(): string { return "new - waiting for payment"; }
}
class PaidState implements State {
public function next(): State { return new ShippedState(); }
public function describe(): string { return "paid - packing the box"; }
}
class ShippedState implements State {
public function next(): State { return $this; }
public function describe(): string { return "shipped - on its way"; }
}
class Order {
public function __construct(private State $state) {}
public function advance(): void {
$this->state = $this->state->next();
}
public function describe(): string {
return $this->state->describe();
}
}
$order = new Order(new NewState());
echo $order->describe(), "\n";
$order->advance();
echo $order->describe(), "\n";
$order->advance();
echo $order->describe(), "\n";
When to Use It
Use it when an object's behavior genuinely differs by state and the states have real rules about transitions — orders, documents (draft/review/published), connections, game characters.
Skip it when a status is only displayed, never changes behavior. A string property and one match is fine below three states with simple rules.
Pros and Cons
Pros: each state's rules live in one small class; impossible transitions are simply not written; new states extend instead of modifying.
Cons: many tiny classes for simple machines; the flow of the whole machine is spread across files — a diagram in a comment helps.