Skip to content

Instantly share code, notes, and snippets.

@iluuu1994
Created September 6, 2020 18:38
Show Gist options
  • Save iluuu1994/cd8d6cf583daf2b97410720e64097a74 to your computer and use it in GitHub Desktop.
Save iluuu1994/cd8d6cf583daf2b97410720e64097a74 to your computer and use it in GitHub Desktop.
Compiled enums
<?php
enum Option {
case None;
case Some(mixed $value) {
public function availableForSome() {
var_dump($this->value);
}
};
public function availableForBoth() {}
}
// Compiled to
class Option {
public function availableForBoth() {}
public static function None() {
// Return singleton here instead
return new None();
}
public static function Some(mixed $value) {
return new Some($value);
}
}
class None extends Option {}
class Some extends Option {
public function __construct(
public mixed $value,
) {}
public function availableForSome() {
var_dump($this->value);
}
}
// Or
class Option {
private function __construct(
private int $discriminator,
private array $associatedValues,
) {}
public static function None() {
// Return singleton here instead
return new self(0, []);
}
public static function Some(mixed $value) {
return new self(1, [$value]);
}
public function availableForBoth() {}
public function availableForSome() {
if ($this->discriminator === 1) {
// ...
} else {
throw new WhateverError();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment