三元运算符中的多个条件安全吗?

问题描述:

我已经看到建议说三元运算符一定不能嵌套。

I have seen advice that says the ternary operator must not be nested.

我已经测试了下面的代码,它可以正常工作。我的问题是,我以前从未见过像这样使用三元运算符。因此,这是否和 if 中所使用的方法一样可靠,还是以后会出现这样的问题并咬我(不是术语或可读性,而是失败)。

I have tested the code below and it works okay. My question is, I haven't seen the ternary operator used like this before. So, is this as reliable as it were used in an if or could something like this come and bite me later(not in terms or readability, but by failing).

$rule1 = true;
$rule2 = false;
$rule3 = true;

$res = (($rule1 == true) && ($rule2 == false) && ($rule3 == true)) ? true : false;

if($res) {
    echo "good";        
} else {
    echo "fail";
}

谢谢!

如果您从三元运算符返回的结果仅为 true和 false,那么您甚至不需要运算符。您可以拥有:

If the results you are returning from the ternary operator are only "true" and "false", then you don't even need the operator. You can just have:

$res = (($rule1 === true) && ($rule2 === false) && ($rule3 === true))

但是,要回答您的问题问题,是的,多个条件都能很好地工作。

But, to answer your question, yes multiple conditions work perfectly well.