How to create a complex enum with data and methods
masterEnums in this library are singletons and can hold state. You can define protected constants that contain arrays of data, which are then passed to a protected constructor to initialize instance properties. This allows you to attach behavior (methods) to specific enum instances.
Key characteristics:
- Singletons: Enum instances are not cloneable or serializable.
- Data Mapping: Use
protectedconstants to store the data required for each instance. - Iteration: Use
Planet::values()(or your class name) to iterate over all defined enum members.
use DASPRiD\Enum\AbstractEnum;
/**
* @method static self MERCURY()
* @method static self VENUS()
*/
final class Planet extends AbstractEnum
{
protected const MERCURY = [3.303e+23, 2.4397e6];
protected const VENUS = [4.869e+24, 6.0518e6];
private $mass;
private $radius;
protected function __construct(float $mass, float $radius)
{
$this->mass = $mass;
$this->radius = $radius;
}
public function mass() : float
{
return $this->mass;
}
// ... other methods
}
// Iterating through all values
foreach (Planet::values() as $planet) {
echo $planet->mass();
}