Traits

Enumerations may leverage traits, which will behave the same as on classes. The caveat is that traits used in an enum must not contain properties. They may only include methods and static methods. A trait with properties will result in a fatal error.

<?php

interface Colorful
{
public function
color(): string;
}

trait
Rectangle
{
public function
shape(): string {
return
"Rectangle";
}
}

enum
Suit implements Colorful
{
use
Rectangle;

case
Hearts;
case
Diamonds;
case
Clubs;
case
Spades;

public function
color(): string
{
return match(
$this) {
Suit::Hearts, Suit::Diamonds => 'Red',
Suit::Clubs, Suit::Spades => 'Black',
};
}
}
?>
add a note

User Contributed Notes 1 note

up
10
wervin at mail dot com
6 months ago
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']
To Top