note 129250 added to language.enumerations.traits
| From: | wervin at mail dot com | Date: | Thu, 15 Feb 2024 09:02:16 +0000 |
| Subject: | note 129250 added to language.enumerations.traits | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-221202@lists.php.net to get a copy of this message | ||
One good example of a trait, would be to give a lot of enums a method to retrieve their cases,
values or both.
<?php
trait EnumToArray
{
public static function names(): array
{
return array_column(self::cases(), 'name');
}
public static function values(): array
{
return array_column(self::cases(), 'value');
}
public static function asArray(): array
{
if (empty(self::values())) {
return self::names();
}
if (empty(self::names())) {
return self::values();
}
return array_column(self::cases(), 'value', 'name');
}
}
?>
Some example outputs:
<?php
var_export(IpVersion::names()); // ['Ipv4', 'IPv6']
var_export(IpVersion::values()); // []
var_export(IpVersion::asArray()); // ['IPv4', 'IPv6']
var_export(Language::names()); // ['en', 'es']
var_export(Language::values()); // ['English', 'Spanish']
var_export(Language::asArray()); // ['en' => 'English', 'es'
=> 'Spanish']
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.13.131 (proxied: 92.68.89.245)
----
Manual Page -- https://php.net/manual/en/language.enumerations.traits.php
Edit -- https://main.php.net/note/edit/129250
Del: integrated -- https://main.php.net/note/delete/129250/integrated
Del: useless -- https://main.php.net/note/delete/129250/useless
Del: bad code -- https://main.php.net/note/delete/129250/bad+code
Del: spam -- https://main.php.net/note/delete/129250/spam
Del: non-english -- https://main.php.net/note/delete/129250/non-english
Del: in docs -- https://main.php.net/note/delete/129250/in+docs
Del: other reasons-- https://main.php.net/note/delete/129250
Reject -- https://main.php.net/note/reject/129250
Search -- https://main.php.net/manage/user-notes.php