IF 语句中值之前或之后的变量
这两个语句之间有区别吗:
if ($a == 'hello') { ... }
和
if ('hello' == $a) { ... }
我注意到像 Wordpress 这样的应用程序倾向于使用后者,而我通常使用前者。
我似乎记得不久前读过一些文章,为后者提供了理由,但我不记得其背后的推理。
Is there a difference between these two statements:
if ($a == 'hello') { ... }
and
if ('hello' == $a) { ... }
I've noticed applications like Wordpress tend to use the latter, whereas I usually use the former.
I seem to remember reading something a while ago giving justification for the latter, but I can't recall the reasoning behind it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有什么区别。使用它是为了在您不小心进行赋值而不是比较时抛出错误:
if($a = 'hello')
将赋值给变量并且不会抛出错误。它也可以用来明确地表明if您在
if
语句中进行了赋值,您确实希望将它放在那里并且这不是一个错误(一致性)。There is no difference. It is used so that an error is thrown in case you accidentally make an assignment instead of a comparison:
if($a = 'hello')
would assign to the variable and not throw an error.It might also be used to explicitly show that if you have an assignment in an
if
statement, you really want to have it there and it is not a mistake (consistency).后者的理由是,如果您错误地输入
=
而不是==
(赋值而不是比较),您将收到编译器错误(无法分配给常量) 。The justifikation for the latter is that if you mistakenly type
=
instead of==
(assignment instead of comparision) you'll get compiler error (can't assign to constant).