php 三元运算符和字符串连接怪癖?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1317383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ternary operator and string concatenation quirk?
提问by Cesar
Hi I just want to know why this code yields (at least for me) an incorrect result.
嗨,我只想知道为什么这段代码会产生(至少对我而言)不正确的结果。
Well, probably i'm in fault here
好吧,可能是我错了
$description = 'Paper: ' . ($paperType == 'bond') ? 'Bond' : 'Other';
I was guessing that if paperType equals 'Bond' then description is 'Paper: Bond' and if paperType is not equals to 'Bond' then description is 'Paper: Other'.
我在猜测,如果 paperType 等于“Bond”,则描述为“Paper: Bond”,如果 paperType 不等于“Bond”,则描述为“Paper: Other”。
But when I run this code the results are description is either 'Bond' or 'Other' and left me wondering where the string 'Paper: ' went???
但是当我运行这段代码时,结果描述是“Bond”或“Other”,让我想知道字符串“Paper:”去哪儿了???
回答by meder omuraliev
$description = 'Paper: ' . ($paperType == 'bond' ? 'Bond' : 'Other');
Try adding parentheses so the string is concatenated to a string in the right order.
尝试添加括号,使字符串以正确的顺序连接到字符串。
回答by Jo?o Silva
It is related with operator precedence. You have to do the following:
它与运算符优先级有关。您必须执行以下操作:
$description = 'Paper: ' . (($paperType == 'bond') ? 'Bond' : 'Other');
回答by hizmarck
I think everyone gave the solution, I would like to contribute the reason for the unexpected result.
我想每个人都给出了解决方案,我想贡献出意外结果的原因。
First of all here you can check the origin, and how the operators are evaluated (left, right, associative, etc).
首先,您可以在此处检查原点以及运算符的计算方式(左、右、关联等)。
http://php.net/manual/fa/language.operators.precedence.php
http://php.net/manual/fa/language.operators.precedence.php
Now if we analyze your sentence.
现在,如果我们分析你的句子。
$ paperType = 'bond';
$ description = 'Paper:'. ($ paperType == 'bond')? 'Bond': 'Other';
1) We review the table and find that the parentheses are evaluated first, then the '.' (concatenation) is evaluated and at the end the ternary operator '?', therefore we could associate this as follows:
1) 我们查看表格,发现括号先求值,然后是 '.' (concatenation) 被评估,最后是三元运算符“?”,因此我们可以将其关联如下:
// evaluate the parenthesis ... ($ paperType == 'bond')
$ description = ('Paper:'. 1)? 'Bond': 'Other';
//result
$ description = 'Paper: 1'? 'Bond': 'Other';
2) We now have the ternary operator, we know that a string is evaluated "true"
2)我们现在有了三元运算符,我们知道一个字符串被评估为“真”
// php documentation When converting to boolean, the following values ??are considered FALSE:
// php 文档当转换为布尔值时,以下值被认为是 FALSE:
... the empty string, and the string "0"
...空字符串和字符串“0”
$ description = true? 'Bond': 'Other';
3) Finally
3)最后
$ description = 'bond';
I hope I have clarified the question. Greetings.
我希望我已经澄清了这个问题。你好。

