Originally published on php2rust.dev — part of the PHP to Rust course. View this lesson on the original site.
Enums define a type by listing its variants. Rust enums can hold associated data (like structs per variant), making them more expressive than PHP enums or backed enums.
Rust
enum Color {
Rgb(u8, u8, u8),
Named(String),
}
fn describe(c: &Color) {
match c {
Color::Rgb(r, g, b) => println!("RGB {}, {}, {}", r, g, b),
Color::Named(s) => println!("Named: {}", s),
}
}
fn main() {
let red = Color::Rgb(255, 0, 0);
let custom = Color::Named(String::from("Forest Green"));
describe(&red);
describe(&custom);
}
PHP
<?php
// PHP 8.1+ backed enum (no associated data per variant)
enum Color: string {
case Red = 'red';
case ForestGreen = 'forest green';
}
// For associated data, use classes or unions
$red = Color::Red;
$custom = Color::ForestGreen;
echo $red->value . "\n";
Comparison
- Rust: Enum variants can carry different data types (tuples, structs, etc.).
- PHP: Backed enums (8.1+) map to scalar values; no arbitrary per-variant data.
- Rust:
Color::Rgb(255, 0, 0)andColor::Named("...")are the same enum type. - PHP: For variant-specific data, use classes or interfaces instead of enums.
References
What's next
Next: Defining enums.
From PHP to Rust — Rust Syntax and Functions