简体   繁体   English

PHP的如果/其他速记失败

[英]php if/else shorthand fail

Normal expression works fine, shorthand doesn't. 正则表达式可以正常工作,速记则不能。 Where am I wrong here? 我在哪里错了?

if (isset($var)) $value = $var;
elseif ($str !== 'string') $value = $str;
else $value = null;
// works just fine

$value = (isset($var)) ? $var : ($str !== 'string') ? $str : null;
// only returns $value = $str

Thanks 谢谢

Try with an extra set of brackets around the second shorthand block, $value = (isset($var)) ? $var : (($str !== 'string') ? $str : null); 尝试在第二个速记块周围加上括号, $value = (isset($var)) ? $var : (($str !== 'string') ? $str : null); $value = (isset($var)) ? $var : (($str !== 'string') ? $str : null);

Added this side note... 添加了此边注...

While it's fun trying to squeeze code into one line, it is often better to write it out so that it's easy to read. 尝试将代码压缩到一行很有趣,但通常最好将代码写出来以便于阅读。 Your line of code is compact but takes a while to digest whereas... 您的代码行很紧凑,但需要一段时间才能消化,而...

if (isset($var)) {
   $value = $var;
}
else if ($str !== 'string') {
   $value = $str;
}
else {
   $value = null;
}

... makes it very clear what's going on - you'll thank yourself in a few months when you look back at your code :) ...非常清楚发生了什么-当您回顾代码时,几个月后您将感激不尽:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM