Search code examples
phplaravelphp-8.1

Convert PHP 8.1 Enums to constants


I have this PHP 8.1 Enum Class but when I uploaded my code, my VPS supports up to PHP 8.0.

 enum AssignmentState: string
 {
    case Draft = 'draft';
    case Published = 'published';
    case Graded = 'graded';
 }

And this is how I use it in the controller and Model Respectively

$request->has('status') ? ($status = $request->status) : ($status = AssignmentState::Published->value);
protected $casts = [
    'status' => AssignmentState::class,
];

So how do I backport enums such that they work with PHP 8.0


Solution

  • If you just want PHP 8.0 code without enums or code based on enums, you can use a class with const properties:

     class AssignmentState
     {
        public const Draft = 'draft';
        public const Published = 'published';
        public const Graded = 'graded';
     }
     
     echo AssignmentState::Published;
    

    And then you'll have to remove the ->value bits from the code that relies on this, since you're not working with enums anymore but just plain strings.