PHP:比较 null 中的运算符顺序
我通常这样写:
if ($myvar == null)
但有时我读到这样:
if (null == $myvar)
我记得有人告诉我后者更好,但我不记得为什么。
您知道哪个更好以及为什么?
谢谢, 担
I usually write this:
if ($myvar == null)
but sometimes I read this:
if (null == $myvar)
I remember somebody told me the latter is better but I don't remember why.
Do you know which is better and why?
Thanks,
Dan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果你不小心忘记了其中一个
=
,第二个就会出错。这会将
null
分配给$myvar
并对结果执行if
检查。这将尝试将
$myvar
的值分配给null
并给出错误,因为您无法分配给null
。If you accidentally forget one of the
=
, the second one will give an error.This will assign
null
to$myvar
and perform theif
check on the result.This will try to assign the value of
$myvar
tonull
and give an error because you cannot assign tonull
.这与顺序无关,而是为了避免意外跳过一个
=
,这将导致赋值而不是比较。当使用常量优先约定时,意外跳过会引发错误。It is not about the order, it is about avoiding accidental skipping one
=
, which will result in assignment instead of comparison. When using constant-first convention, accidental skipping will throw an error.这个人可能提到的是关于条件语句的微观优化。例如,在下面的内容中,由于第一个条件已经失败,因此不会评估第二个条件。
然而,你所拥有的,总会被评估。因此顺序并不重要,已经提到的约定就是正确的选择。
What this person may have alluded to was micro optimizations regarding conditional statements. For example, in the following, the second condition would not be evaluated as the first already failed.
However, what you have will always be evaluated. Therefore order doesn't matter, and the convention mentioned already is the way to go.
我见过后者用于帮助避免程序员错误,例如:
这将始终返回 true,而
将抛出错误。
I've seen the latter used to help avoid programmer errors such as:
this will always return true, whereas
will throw an error.
使用赋值运算符
=
代替相等运算符==
是一个常见错误:它实际上将
null
赋给$myvar< /代码>。捕获此逻辑错误的一种方法是在 LHS 上使用常量,这样如果您使用
=
代替==
,您将得到一个常量错误(在本例中为null
) 无法赋值:Using the assignment operator
=
in place of the equality operator==
is a common mistake:which actually assigns
null
to$myvar
. One way to get this logical error caught is to use the constant on the LHS so that if you use=
in place of==
you'll get an error as constants (null
in this case) cannot be assigned values:您可以使用
is_null()
代替。You can use
is_null()
instead.