PHP code example of vjik / php-enum

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

    

vjik / php-enum example snippets


use Vjik\Enum\Enum;

/**
 * @method static self NEW()
 * @method static self PROCESS()
 * @method static self DONE()
 */
final class Status extends Enum
{
    private const NEW = 'new';
    private const PROCESS = 'process';
    private const DONE = 'done';
}

$process = Status::from('process');

$process = Status::tryFrom('process'); // Status object with value "process"
$process = Status::tryFrom('not-exists'); // null

$process = Status::PROCESS();

Status::DONE()->getName(); // DONE
Status::DONE()->getValue(); // done

use Vjik\Enum\Enum;

/**
 * @method static self CREATE()
 * @method static self UPDATE()
 */
final class Action extends Enum
{
    private const CREATE = 1;
    private const UPDATE = 2;

    protected static function data(): array
    {
        return [
            self::CREATE => [
                'tip' => 'Create document',
            ],
            self::UPDATE => [
                'tip' => 'Update document',
            ],
        ];
    }

    public function getTip(): string
    {
        /** @var string */
        return $this->getPropertyValue('tip');
    }
    
    public function getColor(): string
    {
        return $this->match([
            self::CREATE => 'red',
            self::UPDATE => 'blue',
        ]);
    }
    
    public function getCode(): int
    {
        return $this->match([
            self::CREATE => 1,
        ], 99);
    }
}

echo Action::CREATE()->getTip();
echo Action::CREATE()->getColor();
echo Action::CREATE()->getCode();

// [1, 2]
Action::values(); 

// [$createObject, $updateObject]
Action::cases();

Action::isValid(1); // true
Action::isValid(99); // false

echo Status::DONE(); // done