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::HeartsSuit::Diamonds => 'Red',
            
Suit::ClubsSuit::Spades => 'Black',
        };
    }
}
?>

User Contributed Notes

There are no user contributed notes for this page.
PHP8中文手册 站长在线 整理 版权归PHP文档组所有