Saw a post on X (previously Twitter) that inspired me to write about this.
PHP has been copying a lot from Java in the last 10+ years. That includes the type safe enums that was added to PHP 8.1.
But not only did they copy the "normal" type safe enum from Java - they also copied the concept of an enum being a class with all kinds of methods from Java.
That feature can be useful, but it can also be confusing when misused.
PHP:
<?php
enum Normal {
case A;
case B;
case C;
}
enum Crazy: int {
case A = 1;
case B = 2;
case C = 3;
function println() {
echo sprintf("%s(%d)\r\n", $this->name, $this->value);
}
function hi() {
echo "Hi\r\n";
}
}
$e1 = Normal::B;
echo sprintf("%d\r\n", $e1 == Normal::B);
echo sprintf("%s\r\n", $e1->name);
$e2 = Crazy::B;
echo sprintf("%d\r\n", $e2 == Crazy::B);
$e2->println();
$e2->hi();
?>
Java:
public class EFun {
public static enum Normal { A, B, C }
public static enum Crazy {
A(1), B(2), C(3);
private int v;
private Crazy(int v) {
this.v = v;
}
public void println() {
System.out.printf("%s(%d)\n", this, this.v);
}
public void hi() {
System.out.println("Hi");
}
}
public static void main(String[] args) {
Normal e1 = Normal.B;
System.out.println(e1 == Normal.B);
System.out.println(e1);
Crazy e2 = Crazy.B;
System.out.println(e2 == Crazy.B);
e2.println();
e2.hi();
}
}