Originally published on php2rust.dev — part of the PHP to Rust course. View this lesson on the original site.

Pattern matching on enums lets you handle each variant and extract its data. PHP uses match for backed enums and instanceof or match for class hierarchies.

Rust

enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

fn handle(msg: Message) {
    match msg {
        Message::Quit => println!("Quit message"),
        Message::Move { x, y } => println!("Move to x: {}, y: {}", x, y),
        Message::Write(text) => println!("Write: {}", text),
        Message::ChangeColor(r, g, b) => println!("Color: ({}, {}, {})", r, g, b),
    }
}

fn main() {
    let inbox = [
        Message::Quit,
        Message::Move { x: 10, y: 20 },
        Message::Write(String::from("Hi")),
        Message::ChangeColor(0, 128, 255),
    ];
    for msg in inbox {
        handle(msg);
    }
}

PHP

<?php
enum SimpleMessage: string {
    case Quit = 'quit';
    case Write = 'write';
}

$msg = SimpleMessage::Write;
match ($msg) {
    SimpleMessage::Quit => print("Quit message\n"),
    SimpleMessage::Write => print("Write message\n"),
};

// With classes
$msg = new Move(10, 20);
if ($msg instanceof Move) {
    echo "Move to x: {$msg->x}, y: {$msg->y}\n";
}

Comparison

  • Rust: match is exhaustive; all enum variants must be handled.
  • PHP: match on enums is exhaustive; instanceof handles class hierarchies.
  • Rust: Destructuring in patterns binds variant data to variables.
  • PHP: Access properties directly after instanceof checks.

References

What's next

Next: Destructuring enums.

From PHP to Rust — Rust Syntax and Functions