我有基本的列舉
enum Fruit
{
case APPLE;
case ORANGE;
case BANANA;
}
以及一些使用該列舉鍵入的函式:
function eatFruit (Fruit $fruit)
{
// do stuff
}
和具有未知內容的變數
$fruit = $_POST['fruit']; // user choosed "MILK"
if (?????) { // how to check if it's fruit?
eatFruit($fruit); // this should not be executed
}
我在檔案中找不到檢查列舉是否包含特定情況的簡單方法。
像這樣的支持列舉是可能的
enum Fruit
{
case APPLE = 'APPLE';
case ORANGE = 'ORANGE';
case BANANA = 'BANANA';
}
Fruit::from('');
Fruit::tryFrom('');
這將起作用,但from在我的第一個示例中的非支持列舉上不存在。
Fatal error: Uncaught Error: Call to undefined method Fruit::from()
uj5u.com熱心網友回復:
您可以cases()為此使用靜態方法。這將回傳列舉中所有值的陣列。這些值有一個“名稱”屬性,它是您可以檢查的字串表示形式(支持的列舉也有一個“值”屬性,其中包含您在列舉中定義的字串值)。
所以一個示例實作可能是這樣的:
enum Fruit {
case APPLE;
case ORANGE;
case BANANA;
}
// String from user input
$fruit = $_POST['fruit'];
// Find matching fruit in all enum cases
$fruits = Fruit::cases();
$matchingFruitIndex = array_search($fruit, array_column($fruits, "name"));
// If found, eat it
if ($matchingFruitIndex !== false) {
$matchingFruit = $fruits[$matchingFruitIndex];
eatFruit($matchingFruit);
} else {
echo $fruit . " is not a valid Fruit";
}
function eatFruit(Fruit $fruit): void {
if ($fruit === Fruit::APPLE) {
echo "An apple a day keeps the doctor away";
} elseif ($fruit === Fruit::ORANGE) {
echo "When life gives you oranges, make orange juice";
} elseif ($fruit === Fruit::BANANA) {
echo "Banana for scale";
}
}
帶有示例資料的作業版本:https : //3v4l.org/ObD3s
如果您想使用不同的列舉更頻繁地執行此操作,您可以為此撰寫一個輔助函式:
function getEnumValue($value, $enumClass) {
$cases = $enumClass::cases();
$index = array_search($value, array_column($cases, "name"));
if ($index !== false) {
return $cases[$index];
}
return null;
}
$fruit = getEnumValue($_POST['fruit'], Fruit::class);
if ($fruit !== null) {
eatFruit($fruit);
} else {
echo $_POST['fruit'] . " is not a valid Fruit";
}
具有相同樣本資料的示例:https : //3v4l.org/bL8Wa
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/407233.html
標籤:
