Skip to content

Instantly share code, notes, and snippets.

@tvlooy
Last active March 9, 2020 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvlooy/dd15fa6f942b4d4ce9f11e5f6d37e152 to your computer and use it in GitHub Desktop.
Save tvlooy/dd15fa6f942b4d4ce9f11e5f6d37e152 to your computer and use it in GitHub Desktop.
A small PHP userland enum replacement for SplEnum (spl_types)
<?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);
}
}
<?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