EnumBase

Last updated: August 12th, 2023
Release:

The EnumBase abstract class provides some general functionality for creating enumerated classes/values within PHP.

An Example

Creating and using a class of enumerated values is easy:


use Stoic\Utilities\EnumBase;

class Numbers extends EnumBase {
	const ONE = 1;
	const TWO = 2;
	const THREE = 3;
}

$num = new Numbers(Numbers::ONE);

if ($num->is(Numbers::TWO)) {
	echo("This is number 2");
} else {
	echo("The number is: {$num}");
}

Since enumerated values aren't supported in PHP, using a class with constants allows for type-safety. Usage is simple and both string and JSON serialization are built into the class.

Properties

protected static array $constCache Static internal cache of const lookups protected string $name Internal storage for name protected integer $value Internal storage for value protected boolean $serializeAsName Determines whether or not to serialize as name instead of value, defaults to true

Methods

public static EnumBase fromString(string $string, boolean $serializeAsName = true) Returns a new object of the called class using the constant name instead of the value for initialization public static array getConstList() Returns the const lookup for the called class public static EnumBase tryGetEnum(integer|EnumBase $value, string $className) Returns a new object of type $className either using an existing object or integer value (throw exception on failure) public static boolean validName(string $name) Validates a name against the const lookup for the called class public static boolean validValue(integer $value) Validates a value against the const lookup for the called class public EnumBase __construct(null|integer $value = null, boolean $serializeAsName = true) Instantiates a new object of the called class with option value/serialization settings public string __toString() Serializes the object to its string representation (name or value based on EnumBase::$serializeAsName) public string getName() Retrieves the set name for the object public integer getValue() Retrieves the set value for the object public boolean is(integer $value) Determines if the set value for the object is the same as the supplied value public boolean isIn(integer ...$values) Determines if the current value is equal to any of the supplied values public string jsonSerialize() Serializes the object to its string representation for a json_encode() call (name or value based on EnumBase::$serializeAsName)

Next Up

Continue to read about the I/O component, or visit the Table of Contents.