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

发布于 2024-09-29 17:00:04 字数 191 浏览 5 评论 0原文

我通常这样写:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

红尘作伴 2024-10-06 17:00:04

如果你不小心忘记了其中一个=,第二个就会出错。

if ($myvar = null)

这会将 null 分配给 $myvar 并对结果执行 if 检查。

if (null = $myvar)

这将尝试将 $myvar 的值分配给 null 并给出错误,因为您无法分配给 null

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.

if (null = $myvar)

This will try to assign the value of $myvar to null and give an error because you cannot assign to null.

手长情犹 2024-10-06 17:00:04

这与顺序无关,而是为了避免意外跳过一个 =,这将导致赋值而不是比较。当使用常量优先约定时,意外跳过会引发错误。

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.

天生の放荡 2024-10-06 17:00:04

这个人可能提到的是关于条件语句的微观优化。例如,在下面的内容中,由于第一个条件已经失败,因此不会评估第二个条件。

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

然而,你所拥有的,总会被评估。因此顺序并不重要,已经提到的约定就是正确的选择。

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.

指尖上得阳光 2024-10-06 17:00:04

我见过后者用于帮助避免程序员错误,例如:

if($myvar = null)

这将始终返回 true,而

if(null = $myvar)

将抛出错误。

I've seen the latter used to help avoid programmer errors such as:

if($myvar = null)

this will always return true, whereas

if(null = $myvar)

will throw an error.

奈何桥上唱咆哮 2024-10-06 17:00:04

使用赋值运算符 = 代替相等运算符 == 是一个常见错误:

if($myvar = null)

它实际上将 null 赋给 $myvar< /代码>。捕获此逻辑错误的一种方法是在 LHS 上使用常量,这样如果您使用 = 代替 == ,您将得到一个常量错误(在本例中为 null) 无法赋值:

Using the assignment operator = in place of the equality operator == is a common mistake:

if($myvar = null)

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:

爱的故事 2024-10-06 17:00:04

您可以使用 is_null() 代替。

You can use is_null() instead.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文