PHP三元运算符说明 [英] PHP Ternary operator clarification

查看:108
本文介绍了PHP三元运算符说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常使用三元运算符,但是我在文档中找不到任何有关此的东西,我一直对此感到疑惑.

I use the ternary operator quite often but I've not been able to find anything in the documentation about this and I've always wondered it.

以下是一个可能的示例:

The following is a possible example:

echo ($something->message ? $something->message : 'no message');

如您所见,

如果$ something-> message是正确的,我们返回$ something-> message,但是为什么要写两次呢?有没有办法做类似的事情:

as you can see, if $something->message is correct, we return $something->message, but why write it twice? Is there a way to do something like:

echo ($something->message ? this : 'no message');

现在,我对编程理论并不精通,因此有可能存在一个原因,即前者不能用 之类的"this"进行引用,但为什么不这样做呢?这会不会简化三元运算符的使用?对于我的示例来说,它是毫无用处的,但可以说它是

Now I'm not well versed in programming theory, so it's possible that there is a reason that the former cannot be referenced with something like "this" but why not? Would this not stream line the use of the ternary operator? For something like my example it's pretty useless, but let's say it's

echo (function(another_function($variable)) ? function(another_function($variable)) : 'false');

我找不到任何任何方法来执行此操作,因此我假设这是不可能的,如果我错了,请通知我,否则:为什么不呢?为什么这是不可能的,技术原因是什么,还是仅仅是从未发生过的事情?我应该将其声明为变量,然后针对该变量进行测试吗?

I'm unable to find any way to do this, so I'm assuming it's not possible, if I'm wrong please inform me, otherwise: why not? Why is this not possible, what's the technical reason, or is it just something that never happened? Should I be declaring it as a variable and then testing against that variable?

推荐答案

自PHP 5.3起,可以省略三元运算符的中间部分.表达式expr1?:如果expr1的计算结果为TRUE,则expr3返回expr1,否则返回expr3.

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

来源

例如

$used_value = function1() ?: $default_value;

$check_value = function1(); //doesn't re-evaluate function1()
if( $check_value ) {
    $used_value = $check_value;
} else {
    $used_value = $default_value;
}

明智的话

如果您要依赖于TRUE的类型转换,那么重要的是要了解什么将对TRUE进行类型转换,而不会.可能值得重新研究PHP的类型变戏法并阅读类型转换表.例如(bool)array()FALSE.

If your going to be depending on typecasting to TRUE it's important to understand what WILL typecast to TRUE and what won't. It's probably worth brushing up on PHP's type juggling and reading the type conversion tables. For example (bool)array() is FALSE.

这篇关于PHP三元运算符说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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