class Enum
{
private string $value;
protected function __construct(string $value)
{
$reflectionClass = new ReflectionClass(static::class);
$constants = $reflectionClass->getConstants();
$values = array_values($constants);
if (!in_array($value, $values, true)) {
throw new Exception('Unsupported enum value');
}
$this->value = $value;
}
public function getValue(): string
{
return $this->value;
}
}
class Enum
{
private static string $value;
protected function __construct(string $value)
{
self::$value = $value;
}
public static function getValue(): string
{
return self::$value;
}
}
final class TextHAlign extends Enum
{
private const LEFT = 'left';
private const CENTER = 'center';
private const RIGHT = 'right';
public static function LEFT(): self
{
return new self(self::LEFT);
}
public static function CENTER(): self
{
return new self(self::CENTER);
}
public static function RIGHT(): self
{
return new self(self::RIGHT);
}
}
class Test
{
// ....
protected string $TextHAlign;
// ...
public function setTextHAlign(TextHAlign $HAlign): self
{
$this->TextHAlign = $HAlign::getValue();
return $this;
}
}
(new Test())
->setTextHAlign(TextHAlign::CENTER());