Trait

枚举也能使用 trait,行为和 class 一样。 留意在枚举中 use trait 不允许包含属性。 只能包含方法、静态方法。 包含属性的 trait 会导致 fatal 错误。

<?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',
        };
    }
}
?>
add a noteadd a note

User Contributed Notes

There are no user contributed notes for this page.

备份地址:http://www.lvesu.com/blog/php/language.enumerations.traits.php