-
-
Notifications
You must be signed in to change notification settings - Fork 131
Closed
Labels
Description
To do this, I had to expand Enum to support null values.
It is also a good idea to support null as a separate enum value.
I recommend to use array_key_exist() instead of isset() for validate Enum value:
New:
public static function __callStatic($name, $arguments)
{
$array = static::toArray();
if (\array_key_exists($name, $array)) {
return new static($array[$name]);
}
throw new \BadMethodCallException("No static method or enum constant '$name' in class " . \get_called_class());
}Example:
<?php
final class MyEnum extends \MyCLabs\Enum\Enum
{
public const UNDEFINED = null;
}I can put null to __construct()
<?php
/** @var string|int|null $value */
$enum = new MyEnum($value); // It can take nullBut i cant do it with static:
<?php
$enum = MyEnum::UNDEFINED(); // I'll catch an exceptionAnd finally i can remove excess ? operator from methods and constructors:
This is look better
public function someMethod(MyEnum $enum)
{
if (!$enum->equals(MyEnum::UNDEFINED()) {
// ...
}
}then this
<?php
public function someMethod(?MyEnum $enum)
{
if ($enum !== null) {
// do ...
}
}