枚举扩展或使用特征(可重用性)

Rom*_*LTU 3 php enums laravel php-8.1

我的枚举必须具有用于翻译目的的附加方法:

<?php

declare(strict_types=1);

namespace App\Enums;

enum GenderEnum: string
{
    case MALE = 'male';
    case FEMALE = 'female';

    public function trans(): string
    {
        return trans('enums.' . $this->value);
    }
}
Run Code Online (Sandbox Code Playgroud)

这个方法是反式的,它会在所有枚举中重复,我怎样才能避免重复?我无法使用枚举中的特征来扩展它。

小智 7

枚举不能扩展,也不能继承

但你可以使用Traits,只要该特征不声明任何属性