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

Like structs, Rust enums can have methods and associated functions defined in impl blocks. PHP enums can have methods as well.

Rust

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

impl Message {
    fn call(&self) {
        match self {
            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 {
        msg.call();
    }
}

PHP

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

    public function call(): void {
        match ($this) {
            self::Quit => print("Quit message\n"),
            self::Write => print("Write message\n"),
        };
    }
}

$msg = Message::Write;
$msg->call();

Comparison

  • Rust: impl block on the enum; methods can use match to handle variants.
  • PHP: Methods defined on the enum; match ($this) or switch for behaviour per variant.
  • Rust: Methods receive &self, &mut self, or self; associated functions use ::.
  • PHP: Methods use $this; static methods for associated-function style.

References

What's next

Next: Control flow constructs.

From PHP to Rust — Rust Syntax and Functions