Details
Enums with properties
Documentation
Basic usage
You can found documentation for basic usage here: consistence/consistence docs.
Implementation
You can easily define properties for enum values.
<?php
class CardColor extends \Mesour\Enum\Enum
{
public const BLACK = ['black', true];
public const RED = ['red', false];
/ @var bool */
private $dashed;
public function __construct(string $value, bool $dashed)
{
parent::__construct($value);
$this->dashed = $dashed;
}
public function isDashed(): bool
{
return $this->dashed;
}
}
$red = CardColor::get(CardColor::RED);
$red->getValue(); // 'red'
$red->isDashed(); // false
$black = CardColor::get(CardColor::BLACK);
$red->isDashed(); // true
$availableValues = CardColor::getAvailableValues(); // ['black', 'red']
Comparing
Once you have an enum instance, you can compare them in multiple ways:
<?php
$red = CardColor::get(CardColor::RED);
$red2 = CardColor::get(CardColor::RED);
$black = CardColor::get(CardColor::BLACK);
// by instance
$red === $red; // true
$red === $red2; // true
$red === $black; // false
// with method
$red->equals($red); // true
$red->equals($red2); // true
$red->equals($black); // false
// by value
$red->equalsValue(CardColor::RED); // true
$red->equalsValue('red'); // true
$red->equalsValue(CardColor::BLACK); // false
Default values
You can use default values in constructor and simplify code.
<?php
class CardColor extends \Mesour\Enum\Enum
{
public const BLACK = ['black', true];
public const RED = ['red'];
public const BLUE = 'blue'; // same as ['blue']
/ @var bool */
private $dashed;
public function __construct(string $value, bool $dashed = false)
{
parent::__construct($value);
$this->dashed = $dashed;
}
// ...
}
$blue = CardColor::get(CardColor::BLUE);
$blue->isDashed(); // false
|
Name: |
PHP Enum Value |
Base name: |
enum-class |
Description: |
Create enumerated value objects from constants |
Version: |
- |
PHP version: |
5 |
License: |
Custom (specified in a license file) |
|
|
|
Applications that use this package |
|
No pages of applications that use this class were specified.
If you know an application of this package, send a message to the author to add a link here.
|
Files |
|
File |
Role |
Description |
en (1 file) |
File |
Role |
Description |
index.md |
Doc. |
Documentation |
File |
Role |
Description |
Mesour (1 directory) |
File |
Role |
Description |
Enum (1 file, 1 directory) |
File |
Role |
Description |
EnumTests (1 file, 1 directory) |