以这种方式订购 if 语句的原因是什么?

发布于 2024-10-05 16:39:32 字数 366 浏览 0 评论 0原文

为什么要形成像...

if (null === $this->foo){...}
if (0 === count($bar)){...}

而不是...这样的

if ($this->foo === null){...}
if (count($bar) === 0){...}

if 语句?我在我尊重的许多编码员和项目的代码中注意到了这一点,但我不知道他们为什么这样做。我采用第二种方式,因为它遵循我的想法“如果这个值与 null 相同,那么......”,而询问“如果 null 与这个值相同......”对我来说似乎不太明显。那么...为什么?

Why form if statements like...

if (null === $this->foo){...}
if (0 === count($bar)){...}

rather than...

if ($this->foo === null){...}
if (count($bar) === 0){...}

I've noticed this in the code of a number of coders and projects I respect but I don't know why they do it this way. I do it the second way as it follows my thinking "If this value is identical to null then..." whereas asking "If null is identical to this value..." seems a bit less obvious to me. So... why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

云裳 2024-10-12 16:39:32

它的目的是确保您不会意外地使用 if(this->foo = null) 而不是 double ==。

这是 PHP 会自动为您捕获的错误,

if (null = $foo) {}

而这可能是一个错误(尽管有时可能是故意的并且有用)

if ($foo = null) {}

因此,通过以这种方式排序您的条件,您可以防止意外分配值而不是比较它们。

It's intended to ensure that you don't accidentally put if(this->foo = null) instead of the double ==.

This is an error which PHP will catch for you automatically

if (null = $foo) {}

while this is probably a mistake (although it can be deliberate and useful sometimes)

if ($foo = null) {}

So, by ordering your conditions in such a way, you protect yourself against accidentally assigning a value instead of comparing them.

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