<?php // declare(strict_types=1); trait changed_tryFrom { public static function changed_tryFrom(mixed $value): self|null { if ($value instanceof self) { // nothing to do, already a valid "self". return $value; } elseif (null === $value) { // A backed enum of type int or type string can never contain the null value. // Prevent warning "Passing null to parameter #1 ($value) of type string|int is deprecated". return null; } try { return self::from($value); } catch (\Throwable $ex) { return null; } } } enum SuitAsInt: int { use \changed_tryFrom; case Clubs = 1; case Diamonds = 2; case Hearts = 3; case Spades = 4; } enum SuitAsString: string { use \changed_tryFrom; case Clubs = '1'; case Diamonds = '2'; case Hearts = '3'; case Spades = '4'; } $testcases = [ new \DateTimeImmutable(), null, 4, 4.0, '4', \SuitAsInt::Spades, \SuitAsString::Spades, ]; foreach ($testcases as $testcase) { echo '----------------------------------------'."\n"; echo '--------------[ TESTCASE ]--------------'."\n"; echo '----------------------------------------'."\n"; var_dump($testcase); echo "\n"; echo '------- [ INT backed enum ] -------'."\n"; echo '--- SuitAsInt::tryFrom()'."\n"; try { $value = \SuitAsInt::tryFrom($testcase); if (null !== $value) { echo 'Value is '.$value->name.' with value '.$value->value.'.'."\n"; } else { echo 'Value is NULL.'."\n"; } } catch (\Throwable $exception) { echo $exception::class, ': ', $exception->getMessage(), "\n"; } echo '--- SuitAsInt::changed_tryFrom() [CHANGED]'."\n"; try { $value = \SuitAsInt::changed_tryFrom($testcase); if (null !== $value) { echo 'Value is '.$value->name.' with value '.$value->value.'.'."\n"; } else { echo 'Value is NULL.'."\n"; } } catch (\Throwable $exception) { echo $exception::class, ': ', $exception->getMessage(), "\n"; } echo "\n"; echo '------- [ STRING backed enum ] -------'."\n"; echo '--- SuitAsString::tryFrom()'."\n"; try { $value = \SuitAsString::tryFrom($testcase); if (null !== $value) { echo 'Value is '.$value->name.' with value '.$value->value.'.'."\n"; } else { echo 'Value is NULL.'."\n"; } } catch (\Throwable $exception) { echo $exception::class, ': ', $exception->getMessage(), "\n"; } echo '--- SuitAsString::changed_tryFrom() [CHANGED]'."\n"; try { $value = \SuitAsString::changed_tryFrom($testcase); if (null !== $value) { echo 'Value is '.$value->name.' with value '.$value->value.'.'."\n"; } else { echo 'Value is NULL.'."\n"; } } catch (\Throwable $exception) { echo $exception::class, ': ', $exception->getMessage(), "\n"; } echo "\n"; echo "\n"; }
You have javascript disabled. You will not be able to edit any code.