Last active
March 9, 2020 20:19
-
-
Save tvlooy/dd15fa6f942b4d4ce9f11e5f6d37e152 to your computer and use it in GitHub Desktop.
A small PHP userland enum replacement for SplEnum (spl_types)
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 | |
namespace SomeDomain; | |
use Ctors\Enum; | |
class Company extends Enum | |
{ | |
public const GOOGLE = 'Google'; | |
public const TWITTER = 'Twitter'; | |
public const FACEBOOK = 'Facebook'; | |
// Optional: default value | |
public function __construct($value = null) | |
{ | |
parent::__construct($value ?? self::GOOGLE); | |
} | |
// Optional: factory methods | |
public function GOOGLE(): self | |
{ | |
return new self(self::GOOGLE); | |
} | |
} |
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 | |
namespace Ctors; | |
abstract class Enum | |
{ | |
protected string $value; | |
public function __construct(string $value) | |
{ | |
$classConstants = (new \ReflectionClass(static::class))->getConstants(); | |
if ('' === $value) { | |
throw new \LogicException('Emum can\'t have a blank value'); | |
} | |
if (! \in_array($value, array_values($classConstants), false)) { | |
throw new \LogicException('Value not a const in enum '.static::class); | |
} | |
$this->value = $value; | |
} | |
public function __toString() | |
{ | |
return (string) $this->value; | |
} | |
// Optional: if you need to list all possible values | |
public function allValues(): array | |
{ | |
return (new \ReflectionClass(static::class))->getConstants(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment