三元运算符中的多个条件安全吗? [英] Multiple conditions in the ternary operator safe?

查看:64
本文介绍了三元运算符中的多个条件安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于三元运算符中的多个条件安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆