Skip to content

Instantly share code, notes, and snippets.

@Azer5C74
Created April 18, 2023 14:58
Show Gist options
  • Save Azer5C74/adf7e24cc7674c949edad6d545d1345b to your computer and use it in GitHub Desktop.
Save Azer5C74/adf7e24cc7674c949edad6d545d1345b to your computer and use it in GitHub Desktop.
In this example each case in the WheelSize enum class has a $price property and a constructor that initializes the property. The getPrice() method is used to retrieve the price of a particular enum case. The $wheelSizePrices associative array maps prices to the corresponding WheelSize enum cases.
<?php
enum WheelSize: int
{
case size_20 = 20;
case size_24 = 24;
case size_28 = 28;
private int $price;
public function __construct(int $price)
{
$this->price = $price;
}
public function getPrice(): int
{
return $this->price;
}
}
// create a mapping of prices to enum cases
$wheelSizePrices = [
100 => WheelSize::size_20,
200 => WheelSize::size_24,
300 => WheelSize::size_28
];
// map a price to the enum class
$price = 100;
if (isset($wheelSizePrices[$price])) {
$wheelSizeEnum = $wheelSizePrices[$price];
} else {
throw new InvalidArgumentException("Invalid wheel size price: $price");
}
// get the price of the mapped enum case
$price = $wheelSizeEnum->getPrice();
>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment