以这种方式订购 if 语句的原因是什么?
为什么要形成像...
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它的目的是确保您不会意外地使用 if(this->foo = null) 而不是 double ==。
这是 PHP 会自动为您捕获的错误,
而这可能是一个错误(尽管有时可能是故意的并且有用)
因此,通过以这种方式排序您的条件,您可以防止意外分配值而不是比较它们。
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
while this is probably a mistake (although it can be deliberate and useful sometimes)
So, by ordering your conditions in such a way, you protect yourself against accidentally assigning a value instead of comparing them.