Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Traits and enumerations

Use an enum to close the set of allowed cases and a trait to share methods between types.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

enum Phase: string { use Display; case Ready = "R"; }

Use an enum to close the set of allowed cases and a trait to share methods between types. Each enum case is a singleton. A backed case exposes its scalar value to the imported instance method through $this. An enum may use a trait with methods but cannot use one that declares properties.

trait Display{public function label():string{return $this->name.":".$this->value;}} enum Phase:string{use Display;case Ready="R";case Done="D";}
echo json_encode(array_map(fn($p)=>$p->label(),Phase::cases()));
["Ready:R","Done:D"]

Examples

<?php
trait Display{public function label():string{return $this->name.":".$this->value;}} enum Phase:string{use Display;case Ready="R";case Done="D";}
echo json_encode(array_map(fn($p)=>$p->label(),Phase::cases()));

Result

["Ready:R","Done:D"]

Sources