Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enums extend or use traits (reusability)

I have enums that must have additional methods for translation purposes:

<?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);
    }
}

This method is trans and it will be duplicated in all enums, how can I avoid duplication? I can't extend it using traits in enums.

like image 646
RomkaLTU Avatar asked Sep 16 '25 22:09

RomkaLTU


1 Answers

Enum cannot be extended, and must not inherit

but you can use Traits, as long as the trait does not declare any properties

like image 152
Riccardo Venturini Avatar answered Sep 18 '25 14:09

Riccardo Venturini