如何编写 PHP 三元运算符

2022-08-30 08:35:19

如何使用 elseif 部分编写 PHP 三元运算符?

我看到PHP三元运算符的和部分的基本示例,如下所示:ifelse

echo (true)  ? "yes" : "no";    //prints yes
echo (false) ? "yes" : "no";    //prints no

如何将像这样的“elseif”部分放入三元运算符中?

<?php 
  if($result->vocation == 1){
    echo "Sorcerer"; 
  }else if($result->vocation == 2){
    echo 'Druid';
  }else if($result->vocation == 3){
    echo 'Paladin';
  }else if($result->vocation == 4){
    echo 'Knight';
  }else if($result->vocation == 5){
    echo 'Master Sorcerer';
  }else if($result->vocation == 6){
    echo 'Elder Druid';
  }else if($result->vocation == 7){
    echo 'Royal Paladin';
  }else{
    echo 'Elite Knight';
  }
?>

答案 1

三元对你想要的东西来说不是一个好的解决方案。它在您的代码中不可读,并且有更好的解决方案可用。

为什么不使用数组查找“map”或“字典”,如下所示:

$vocations = array(
    1 => "Sorcerer",
    2 => "Druid",
    3 => "Paladin",
    ...
);

echo $vocations[$result->vocation];

此应用程序的三元组最终将如下所示:

echo($result->group_id == 1 ? "Player" : ($result->group_id == 2 ? "Gamemaster" : ($result->group_id == 3 ? "God" : "unknown")));

为什么这很糟糕?因为 - 作为一条长线,如果这里出现问题,您将无法获得有效的调试信息,长度使其难以阅读,加上多个三元组的嵌套感觉很奇怪。

标准三元形简单易读,如下所示:

$value = ($condition) ? 'Truthy Value' : 'Falsey Value';

echo ($some_condition) ? 'The condition is true!' : 'The condition is false.';

三元其实只是写一个简单语句的一种方便/较短的方式。上面的样本三元数与:if else

if ($some_condition) {
    echo 'The condition is true!';
} else {
    echo 'The condition is false!';
}

然而,复杂逻辑的三元形很快就会变得不可读,不再值得简洁。

echo($result->group_id == 1 ? "Player" : ($result->group_id == 2 ? "Gamemaster" : ($result->group_id == 3 ? "God" : "unknown")));

即使有一些细心的格式来将其分散在多行上,也不是很清楚:

echo($result->group_id == 1 
    ? "Player" 
    : ($result->group_id == 2 
        ? "Gamemaster" 
        : ($result->group_id == 3 
            ? "God" 
            : "unknown")));

答案 2

由于这是一项常见任务,我建议将开关/案例包装在函数调用中。

function getVocationName($vocation){
    switch($vocation){
        case 1: return "Sorcerer";
        case 2: return 'Druid';
        case 3: return 'Paladin';
        case 4: return 'Knight';
        case 5: return 'Master Sorcerer';
        case 6: return 'Elder Druid';
        case 7: return 'Royal Paladin';
        default: return 'Elite Knight';
    }
}

echo getVocationName($result->vocation);

推荐