Created
September 6, 2020 18:38
-
-
Save iluuu1994/cd8d6cf583daf2b97410720e64097a74 to your computer and use it in GitHub Desktop.
Compiled enums
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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