Defaults give you some control over the configuration of the default value.
The basic way to specify a Default
is by adding a case.
enum Suit
{
use Henzeb\Enumhancer\Concerns\Defaults;
case Hearts;
case Clubs;
case Spades;
case Diamonds;
case Default;
}
Suit::default(); // returns Suit::Default
Suit::Default->isDefault(); // returns true
Suit::Default->isNotDefault(); // returns false
Suit::Spades->isDefault(); // returns true
Suit::Spades->isNotDefault(); // returns true
NOTE: the default method returns a null
when no default is set.
Suit::from('default'); // returns Suit::Default
Suit::from('circles'); // throws ValueError
Suit::tryFrom('circles'); // returns Suit::Default
Suit::get('default'); // returns Suit::Default
Suit::get('circles'); // throws ValueError
Suit::tryGet('circles', true); // returns Suit::Default
Suit::tryGet('circles'); // returns null
Everywhere you use the string default
, Enumhancer uses what
ever default you have configured.
Defaults are primarily configured using a constant named
Default
.
enum Suit
{
use Henzeb\Enumhancer\Concerns\Defaults;
case Hearts;
case Clubs;
case Spades;
case Diamonds;
const Default = Suit::Hearts;
}
Suit::default(); // returns Suit::Hearts
Suit::Default->isDefault(); // returns true
Suit::Default->isNotDefault(); // returns false
Suit::Hearts->isDefault(); // returns true
Suit::Hearts->isNotDefault(); // returns false
Suit::Spades->isDefault(); // returns true
Suit::Spades->isNotDefault(); // returns true
Suit::from('default'); // returns Suit::Hearts
Suit::from('circles'); // throws ValueError
Suit::tryFrom('circles'); // returns Suit::Hearts
Suit::get('default'); // returns Suit::Hearts
Suit::get('circles'); // throws ValueError
Suit::tryGet('circles'); // returns Suit::Hearts
NOTE: Be aware that a constant Default
always has to be an
instance of the enum they are in.
When you don't want developers to use the constant directly, you can make the constant private.
enum Suit
{
use Henzeb\Enumhancer\Concerns\Defaults;
case Hearts;
case Clubs;
case Spades;
case Diamonds;
private const Default = Suit::Hearts;
}
Another way to set a default is by overriding the default method.
enum Suit
{
use Henzeb\Enumhancer\Concerns\Defaults;
case Hearts;
case Clubs;
case Spades;
case Diamonds;
public static function default(): ?self
{
return Suit::Spades;
}
}
When the method returns null
, no default is set.
The order of precedence is as follows:
- Overridden
default
method ConfigureDefaults
- mapped values using Mappers
- one of
const
orcase
in order of appearance (uppercase or lowercase)