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()); var_export(IpVersion::values()); var_export(IpVersion::asArray()); var_export(Language::names()); var_export(Language::values()); var_export(Language::asArray());