PHP code example of geoffroy-aubry / enum

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

    

geoffroy-aubry / enum example snippets


class Month extends SplEnum {
    const JANUARY  = 1;
    const FEBRUARY = 2;
}

class Fruit extends SplEnum {
    const APPLE  = 1;
    const ORANGE = 2;
}

// you must create new instance before each use:
$jan   = new Month(Month::JANUARY);
$jan2  = new Month(Month::JANUARY);
$apple = new Fruit(Fruit::APPLE);

var_dump($jan === $jan2);          // false
var_dump($jan === Month::JANUARY); // false
var_dump($jan ==  Fruit::APPLE);   // true



use GAubry\Enum\EnumAbstract;

class ColorEnum extends EnumAbstract {
    public static $RED;
    public static $GREEN;
    public static $BLUE;
}

$color = ColorEnum::RED();
var_dump((string)$color); // string(3) "RED"

function f (ColorEnum $color) {
    switch($color) {
        case ColorEnum::RED():
        …
    }
    …
}

f(ColorEnum::RED());

// One call per enumeration is necessary and sufficient, 
// typically at the top of the program, during instantiation phase:
ColorEnum::buildInstances(); 

$color = ColorEnum::$RED;
var_dump((string)$color); // string(3) "RED"
var_dump(ColorEnum::$RED === ColorEnum::RED()); // true

function f (ColorEnum $color) {
    switch($color) {
        case ColorEnum::$RED:
        …
    }
    …
}

f(ColorEnum::$RED);

class ColorEnum extends EnumAbstract {
    public static $RED = 'red color';
    …
}

var_dump(ColorEnum::values());

var_dump(ColorEnum::keys());

    
    
    
bash
$ curl -sS https://getcomposer.org/installer | php
bash
    $ php vendor/bin/phpmd src/ text codesize,design,unusedcode,naming,controversial