PHP code example of webdevcave / enum-index-accessor

1. Go to this page and download the library: Download webdevcave/enum-index-accessor 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/ */

    

webdevcave / enum-index-accessor example snippets


enum HexColors: string {
    case RED = '#FF0000';
    case GREEN = '#00FF00';
    case BLUE = '#0000FF';
    case WHITE = '#FFFFFF';
    case BLACK = '#000000';
    // and so on...
}

$index = 'BLUE'; // Imagine this is a dynamic value
$constant = HexColors::class."::$index"; // In a real-world application HexColors
                                         // will most probably be declared under a namespace
$color = null;

// Before we proceed, we have to ensure the specified index exists or our code will break
if (defined($constant)) {
    $color = constant($constant)->value; // Now we read its value
}

// You will probably want to assign a default value in case something went wrong
if (is_null($color)) {
    $color = HexColors::RED->value;
}

// Now we can finally proceed with our task...

$color = HexColors::tryValue($index) ?? HexColors::value('RED');

use \WebdevCave\EnumIndexAccessor\BackedEnumIndexAccessor; // step 1: Import the trait

enum HexColors: string {
    case RED = '#FF0000';
    case GREEN = '#00FF00';
    case BLUE = '#0000FF';
    case WHITE = '#FFFFFF';
    case BLACK = '#000000';
    // and so on...
    
    use BackedEnumIndexAccessor; // step 2: use it
}

HexColors::hasIndex($index); // Checks if a case statement was set in the enumerator (boolean)
HexColors::index($index); // Read the object from given index (skips index check)
HexColors::tryIndex($index); // Read the object from given index (null on non-existent)
HexColors::value($index); // Read the value from given index (skips index check)
HexColors::tryValue($index); // Read the value from given index (null on non-existent)

use \WebdevCave\EnumIndexAccessor\PureEnumIndexAccessor; // step 1: Import the trait

enum Fruits {
    case ORANGE;
    case PEAR;
    case APPLE;
    // and so on...
    
    use PureEnumIndexAccessor; // step 2: use it
}