简体   繁体   English

PHP:比较中运算符的顺序为null

[英]PHP: order of operators in a comparison null

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 谢谢,丹

If you accidentally forget one of the = , the second one will give an error. 如果您不小心忘记了其中一个= ,则第二个会出错。

if ($myvar = null)

This will assign null to $myvar and perform the if check on the result. 这将为$myvar分配null并对结果执行if检查。

if (null = $myvar)

This will try to assign the value of $myvar to null and give an error because you cannot assign to null . 这将尝试将$myvar的值$myvar null并给出错误,因为您无法将其赋值为null

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. 例如,在下文中,第二个条件不会被评估为第一个已经失败的条件。

if (1 == 0 && 1 == 1)

However, what you have will always be evaluated. 但是,您所拥有的将始终被评估。 Therefore order doesn't matter, and the convention mentioned already is the way to go. 因此,顺序并不重要,已经提到的惯例是要走的路。

I've seen the latter used to help avoid programmer errors such as: 我已经看到后者用于帮助避免程序员错误,例如:

if($myvar = null)

this will always return true, whereas 这将永远返回true,而

if(null = $myvar)

will throw an error. 会抛出错误。

您可以使用is_null()代替。

Using the assignment operator = in place of the equality operator == is a common mistake: 使用赋值运算符=代替等于运算符==是一个常见的错误:

if($myvar = null)

which actually assigns null to $myvar . 实际上为$myvar指定了null 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: 捕获此逻辑错误的一种方法是使用LHS上的常量,这样如果使用=代替==您将得到一个错误,因为常量(在这种情况下为null )不能赋值:

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

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