PHP code example of fuwasegu / php-enum-util

1. Go to this page and download the library: Download fuwasegu/php-enum-util library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

fuwasegu / php-enum-util example snippets


enum Status: string
{
    use HasDescription;

    case ACTIVE = 'active';

    case INACTIVE = 'inactive';

    case RETIED = 'retired';

    public function description(): string
    {
        return match ($this) {
            self::ACTIVE => 'State in which the employee is enrolled.',
            self::INACTIVE => 'State in which the employee is on administrative leave.',
            self::RETIED => 'State in which employee is retiring.',
        };
    }
}

// Getter for Enum description
Status::ACTIVE->description();

// Getter for Enum value and description maps
Status::descriptions();

enum Capital: int
{
    use HasLabel;

    case TOKYO = 1;

    case BEIJING = 2;

    case WASHINGTON = 3;

    case LONDON = 4;

    public function label(): string
    {
        return match ($this) {
            self::TOKYO => 'Tokyo',
            self::BEIJING => 'Beijing',
            self::WASHINGTON => 'Washington',
            self::LONDON => 'London',
        };
    }
}

// Getter for Enum label
Status::ACTIVE->label();

// Getter for Enum value and label maps
Status::labels();

enum Status: string
{
    use HasValues;

    case ACTIVE = 'active';

    case INACTIVE = 'inactive';

    case RETIED = 'retired';
}

// Getter for Enum values
Status::values();

// Join Enum values with a string
Status::implodeValues();

enum Status: string
{
    use HasNames;

    case ACTIVE = 'active';

    case INACTIVE = 'inactive';

    case RETIED = 'retired';
}

// Getter for Enum names
Status::names();

// Join Enum names with a string
Status::implodeNames();

enum Status: string
{
    use Comparable;

    case ACTIVE = 'active';

    case INACTIVE = 'inactive';

    case RETIED = 'retired';
}

// Compare Enum peer to peer
$maybeActive = Status::ACTIVE;
Status::ACTIVE->is($maybeActive); // true
Status::INACTIVE->isNot($maybeActive); // false

// Attempts to convert the compared int or string to an Enum with Enum::tryFrom before comparing
// If tryFrom is null, `isFrom()` returns false and `isNotFrom()` returns true.
$value = 'active';
Status::ACTIVE->isFrom($value); // true
Status::INACTIVE->isNotFrom($value); // false
Status::ACTIVE->isFrom('foo'); // false
Status::ACTIVE->isNotFrom('foo') // true