note 128925 added to class.backedenum
| From: | php at markuszeller dot com | Date: | Thu, 28 Sep 2023 14:25:50 +0000 |
| Subject: | note 128925 added to class.backedenum | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-220882@lists.php.net to get a copy of this message | ||
If you have a string and want to convert it into a enum, you may find this approach useful:
<?php
enum Company
{
case Acme;
case Meac;
public static function fromName(string $name): self
{
foreach (self::cases() as $case) {
if ($name === $case->name) {
return $case;
}
}
throw new Exception("Invalid Company: $name");
}
}
$comany = Comany::fromName('Acme');
?>
----
Server IP: 45.112.84.4
Probable Submitter: 45.91.157.134 (proxied: 212.3.92.146)
----
Manual Page -- https://php.net/manual/en/class.backedenum.php
Edit -- https://main.php.net/note/edit/128925
Del: integrated -- https://main.php.net/note/delete/128925/integrated
Del: useless -- https://main.php.net/note/delete/128925/useless
Del: bad code -- https://main.php.net/note/delete/128925/bad+code
Del: spam -- https://main.php.net/note/delete/128925/spam
Del: non-english -- https://main.php.net/note/delete/128925/non-english
Del: in docs -- https://main.php.net/note/delete/128925/in+docs
Del: other reasons-- https://main.php.net/note/delete/128925
Reject -- https://main.php.net/note/reject/128925
Search -- https://main.php.net/manage/user-notes.php