小编典典
三元不是您想要的一个很好的解决方案。它不会在您的代码中可读,并且有很多更好的解决方案可用。
为什么不使用数组查找“ map”或“ dictionary”,如下所示:
$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")));
2020-05-26