PHP code example of richard-ejem / enum

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

    

richard-ejem / enum example snippets


class UserRole
{
    use \Ejem\Enum\EnumTrait;
    
    const GUEST = 'guest';
    const USER = 'user';
    const ADMIN = 'admin';
}

class User
{
    /** @var string UserRole enum */
    private $role;
    
    /** @throws \Ejem\Enum\InvalidEnumValueException */
    public function __construct(string $role)
    {
        $this->setRole($role);
    }
    
    public function getRole(): string
    {
        return $this->role;
    }
    
    /** @throws \Ejem\Enum\InvalidEnumValueException */
    public function setRole(string $role): void
    {
        UserRole::assertValidValue($role);
        $this->role = $role;
    }
    
    // ... more user stuff
}


// Validate without throwing exception.
// imagine you are importing users from an old system,
// setting all unsupported roles to GUEST:

$role = UserRole::isValidValue($row['role']) ? $row['role'] : UserRole::GUEST;
    
// Retrieve all possible values.
// Assign random color to a shape

$values = Color::getPossibleValues();
$shape->setColor($values[mt_rand(0, count($values)-1)]);