PHP 8.4.0 RC4 available for testing

Traits

Enums können Traits verwenden, die sich dann genauso verhalten wie in Klassen. Hierbei ist zu beachten, dass die in einer Enum verwendeten Traits keine Eigenschaften enthalten dürfen, sondern nur Methoden und statische Methoden. Ein Trait mit Eigenschaften führt zu einem fatalen Fehler.

<?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
14
wervin at mail dot com
8 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