Welcome back to PHP Design Patterns Game! In this new article, we explore the State Pattern, a behavioral design pattern that allows an object to change its behavior depending on its internal state.
In our previous articles, we explored patterns such as Strategy, Observer, and Adapter through simple games. This time, we will build a small role-playing game where a character can run, attack, become stunned, recover, and eventually die.
The interesting part is not the number of actions our character can perform. It is that the same action may produce a different result depending on the character’s current condition.
A character that is running can attack. A stunned character cannot. A dead character cannot perform any action at all.
Let’s see how the State Pattern helps us organize these rules without creating a large collection of conditional statements.
Understanding the State Pattern
Imagine a game character represented by a class containing a state variable:
private string $state = 'idle';Whenever the player requests an action, the game checks the value of this variable and decides what to do.
Initially, a few conditions might be sufficient. However, as the character gains more abilities and restrictions, the code becomes increasingly difficult to maintain.
Every action may require multiple checks. Adding a new state could force developers to revisit movement, combat, recovery, and damage-handling methods.
The State Pattern proposes a different organization: represent each state with its own object and delegate state-dependent behavior to that object.
The character becomes the context. It maintains a reference to its current state. Each concrete state implements a common interface and defines which actions are permitted and which transitions should occur.
Defining Our Game Rules
Our character will support five states:
- Idle: The character can start running or attacking.
- Running: The character can stop, attack, or be stunned.
- Attacking: The character is performing an attack and must finish before running again.
- Stunned: The character cannot move or attack until recovering.
- Dead: The character can no longer perform actions.
For simplicity, our character begins with two health points. Each successful hit removes one point, and reaching zero immediately changes the state to Dead.
This is a command-line demonstration rather than a graphical game. It is deliberately small so we can concentrate on the design pattern.
Implementing the Game in PHP 8.2+
We will use a backed enumeration to represent player actions. Enumerations were introduced in PHP 8.1 and provide a convenient way to define a fixed collection of allowed commands.
Each state implements the CharacterState interface. The Hero class delegates actions to its current state and controls state transitions.
The following example is complete and can be saved as game.php.
<?php
declare(strict_types=1);
enum Action: string
{
case Run = 'run';
case Attack = 'attack';
case Stop = 'stop';
case Stun = 'stun';
case Recover = 'recover';
case Hit = 'hit';
}
interface CharacterState
{
public function name(): string;
public function handle(Hero $hero, Action $action): string;
}
final class Hero
{
private CharacterState $state;
private int $health = 2;
public function __construct()
{
$this->state = new IdleState();
}
public function act(Action $action): string
{
return $this->state->handle($this, $action);
}
public function state(): string
{
return $this->state->name();
}
public function transition(CharacterState $next): string
{
$previous = $this->state->name();
$this->state = $next;
return "$previous -> {$next->name()}";
}
public function takeHit(): string
{
$this->health--;
return $this->health === 0
? $this->transition(new DeadState())
: "Damage taken: {$this->health} HP left";
}
}
final class IdleState implements CharacterState
{
public function name(): string
{
return 'idle';
}
public function handle(Hero $hero, Action $action): string
{
return match ($action) {
Action::Run => $hero->transition(new RunningState()),
Action::Attack => $hero->transition(new AttackingState()),
Action::Stun => $hero->transition(new StunnedState()),
Action::Hit => $hero->takeHit(),
default => 'Not allowed while idle',
};
}
}
final class RunningState implements CharacterState
{
public function name(): string
{
return 'running';
}
public function handle(Hero $hero, Action $action): string
{
return match ($action) {
Action::Stop => $hero->transition(new IdleState()),
Action::Attack => $hero->transition(new AttackingState()),
Action::Stun => $hero->transition(new StunnedState()),
Action::Hit => $hero->takeHit(),
default => 'Not allowed while running',
};
}
}
final class AttackingState implements CharacterState
{
public function name(): string
{
return 'attacking';
}
public function handle(Hero $hero, Action $action): string
{
return match ($action) {
Action::Stop => $hero->transition(new IdleState()),
Action::Stun => $hero->transition(new StunnedState()),
Action::Hit => $hero->takeHit(),
default => 'Not allowed while attacking',
};
}
}
final class StunnedState implements CharacterState
{
public function name(): string
{
return 'stunned';
}
public function handle(Hero $hero, Action $action): string
{
return match ($action) {
Action::Recover => $hero->transition(new IdleState()),
Action::Hit => $hero->takeHit(),
default => 'Not allowed while stunned',
};
}
}
final class DeadState implements CharacterState
{
public function name(): string
{
return 'dead';
}
public function handle(Hero $hero, Action $action): string
{
return 'Not allowed: character is dead';
}
}
$hero = new Hero();
if (($argv[1] ?? '') === '--demo') {
$script = [
Action::Run, Action::Attack, Action::Run,
Action::Stop, Action::Stun, Action::Attack,
Action::Recover, Action::Hit, Action::Hit,
Action::Attack,
];
foreach ($script as $action) {
printf(
"%-8s | %s\n",
$action->value,
$hero->act($action)
);
}
if ($hero->state() !== 'dead') {
throw new LogicException('Expected dead state');
}
exit;
}
echo "Actions: run, attack, stop, stun, recover, hit, quit\n";
while (true) {
echo '[' . $hero->state() . '] > ';
$line = fgets(STDIN);
if ($line === false || trim($line) === 'quit') {
break;
}
$action = Action::tryFrom(trim($line));
echo (
$action
? $hero->act($action)
: 'Unknown action'
) . PHP_EOL;
}
Running the Game
Save the code in a file named game.php and execute it from the command line:
php game.phpThe game starts in the Idle state and accepts commands such as run, attack, stop, stun, recover, and hit.
Try running, then attacking, then running again without stopping the attack. The final request will be rejected because our AttackingState does not allow that transition.
For a deterministic demonstration, run:
php game.php --demoThe expected output is:
run | idle -> running
attack | running -> attacking
run | Not allowed while attacking
stop | attacking -> idle
stun | idle -> stunned
attack | Not allowed while stunned
recover | stunned -> idle
hit | Damage taken: 1 HP left
hit | idle -> dead
attack | Not allowed: character is deadNotice that the game does not require a central collection of conditions checking every combination of state and action. Each state object defines its own permitted operations.
What Makes This the State Pattern?
Three elements are essential to the design.
First, the Hero object maintains a reference to a CharacterState. This is the context in the State Pattern.
Second, the concrete states implement the same interface. This allows the Hero to handle actions without knowing which particular class currently represents its behavior.
Third, the states can trigger transitions. For example, RunningState can transition to AttackingState when the player requests an attack.
Changing the state object changes how the Hero responds to subsequent actions. The character’s public interface remains the same.
State Pattern Versus Strategy Pattern
If you followed our previous Strategy Pattern article, you may notice that the two patterns have similar structures.
Both rely on composition and delegation. Both define an interface implemented by multiple concrete classes.
The difference is their purpose.
Strategy is primarily concerned with choosing between interchangeable algorithms. In a game, this might involve selecting different combat strategies or navigation algorithms.
State is concerned with how an object’s behavior changes during its lifecycle. A character becomes stunned, recovers, attacks, and eventually dies. These transitions are part of the object’s internal rules.
The distinction becomes particularly visible when concrete states initiate transitions themselves, as they do in our example.
Why Not Just Use a PHP Enum?
PHP enumerations are useful for representing a finite collection of possible values. We used one to define player actions.
We could also use an enum to represent Idle, Running, Attacking, Stunned, and Dead.
For a small game with only a few transitions, that might be the simplest solution.
However, an enum representing the current state does not automatically organize the behavior associated with that state. Developers may still end up implementing large conditional blocks elsewhere.
The State Pattern becomes more useful when each state has substantial behavior, distinctive transitions, and its own rules that are likely to evolve independently.
Limitations of Our Implementation
Our game deliberately keeps the rules simple, but it is not intended to be a complete RPG engine.
For example, attacks do not yet target enemies, the character cannot recover health, and the Stunned state has no duration. The example focuses exclusively on character-state transitions.
The implementation also exposes the transition() method publicly to allow state objects to change the context. In a larger application, this capability should be more tightly controlled to prevent unrelated code from bypassing gameplay rules.
Another tradeoff is the number of classes. Replacing a small conditional statement with five state classes would be unnecessary if the application had only two states and almost no behavior.
Design patterns are useful when they reduce meaningful complexity, not simply when they introduce more objects.
Your Turn: Add a Poisoned State
Let’s extend the game with a small programming challenge.
Add a new state named PoisonedState. When the character becomes poisoned, it should lose one health point after each completed turn. The character should still be able to perform selected actions while poisoned.
Your implementation should also introduce an action that removes the poisoned condition and returns the character to its normal state.
Consider what should happen if the character’s health reaches zero during a poisoned turn. Can your implementation guarantee that DeadState remains terminal?
As an additional exercise, write tests ensuring that invalid transitions are rejected and that each state produces the expected behavior.
Conclusion
The State Pattern provides a useful way to organize objects whose behavior changes according to their internal condition.
By extracting state-specific behavior into separate classes, our game character can evolve without requiring a single class to manage every possible action and transition.
It is not always necessary, but it becomes valuable as the number of states and behavioral rules increases.
In our next PHP Design Patterns Game article, we’ll explore the Decorator Pattern by creating a character whose abilities can be extended with weapons, armor, and temporary power-ups.

















![PHP #[Override]: Catching Broken Inheritance Contracts Before Production](https://phpmagazine.net/wp-content/uploads/2026/11/php-override-218x150.png)






