User Tools

Site Tools


programmieren:php:enums

Enums

Enums, full name Enumerations, are a way to set a list of options “cases” possibly including assigned values.

Enums are classes in PHP, so you can define a class of for example “Currency” with possible options like “CHF”, “EUR”, “USD” etc. Enums by default can be initialized from a corresponding value, or then again fail if the value does not correspond to any values defined in the Enum.

This can be done like so:

Resource::from($data['resource']

The resource in this case could be 'cpu' and would correspond to a case in the enum like so:

enum Resource: string
{
    /** @var string CPU */
    case CPU = 'cpu';
}

So in this case the resource data would be turned into a corresponding Resource enum, whose value can be read out later like so:

$this->resource->value,
programmieren/php/enums.txt · Last modified: by admin

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki