Home > Blockchain >  Convert PHP 8.1 Enums to constants
Convert PHP 8.1 Enums to constants

Time:08-30

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

CodePudding user response:

Try it

abstract class AssignmentState
{
    const DRAFT = 'draft';
    const PUBLISHED = 'published';
    const GRADED = 'graded';
}

in Model

$request->has('status') ? ($status = $request->status) : ($status = AssignmentState::PUBLISHED);

I think, you shouldn't cast status

CodePudding user response:

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.

  • Related