PHP 相等性检查不会抛出错误
我刚刚在 PHP 脚本中发现了以下代码,想知道为什么它没有导致 PHP 报告错误?
$current_name == ($type != 3) ? $name : '' ;
这是一个拼写错误,代码应该是这样的:
$current_name = ($type != 3) ? $name : '' ;
I just found the following code in a PHP script and was wondering why it didn't cause PHP to report an error?
$current_name == ($type != 3) ? $name : '' ;
It was a typo and the code was supposed to read:
$current_name = ($type != 3) ? $name : '' ;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一段奇怪的代码,但只是因为它不可读且无用,而不是因为它无效。它使用三元运算符,基本上是格式为
condition 的简写
。if
构造?如果为真:如果为假此代码执行以下操作:
$type != 3
。如果$type
为3
,则返回false
,否则返回true
。$current_name
进行比较。true
(即$current_name == true
),则返回$name
。否则(即$current_name == false
)返回''
。当然,这一切完全没有任何作用,因为语句中没有赋值。
That is a bizarre bit of code, but only because it is unreadable and useless, not because it is invalid. It uses the ternary operator, which is basically a shorthand
if
construct in the formatcondition ? if true : if false
.This code does the following:
$type != 3
. If$type
is3
, returnfalse
, otherwisetrue
.$current_name
.true
(i.e.$current_name == true
), return$name
. Otherwise (i.e.$current_name == false
) return''
.Of course, all this does absolutely nothing, because there is no assignment in the statement.
它在语法上是正确的。计算三元表达式,然后与
$current_name
进行比较。不使用整个表达式的结果。It is syntactically correct. The ternary expression is evaluated, then compared to
$current_name
. The result of the whole expression is not used.