Skip to content

Instantly share code, notes, and snippets.

@tvlooy tvlooy/Company.php
Last active Mar 16, 2018

Embed
What would you like to do?
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
public function __construct($value = null)
{
parent::__construct($value ?? self::GOOGLE);
}
}
<?php
namespace Ctors;
abstract class Enum
{
protected $value;
public function __construct(string $value)
{
$className = \get_class($this);
$class = new \ReflectionClass($className);
$classConstants = $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 ' . $className);
}
$this->value = $value;
}
public function __toString()
{
return (string) $this->value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.