何时使用 if/endif 与 If{}?
嗯,这个问题是不言自明的。
在 PHP 中,何时使用 if/endif
表示法而不是标准 if(something){}
表示法?
示例:
<?php if($a == 5): ?>
A is equal to 5
<?php endif; ?>
对比:
<?php if($a == 5){ ?>
A is equal to 5
<?php } ?>
Well the question is self explanatory.
In PHP when do I use the if/endif
notation instead of the standard if(something){}
notation?
Example:
<?php if($a == 5): ?>
A is equal to 5
<?php endif; ?>
Versus:
<?php if($a == 5){ ?>
A is equal to 5
<?php } ?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
其他人给出了“用于模板”的答案,但没有真正解释原因。大括号非常适合表示块,但它们有点依赖于缩进才能清晰地阅读。所以这是相当清楚的:
很明显哪个大括号与哪个大括号匹配。
但是,如果您要进入 HTML 块,则可能会完全停止缩进。例如:
这很难理解。如果您使用
endif
样式,它看起来会更干净一些:代码的内容更清楚地显示正在执行的操作。对于这种有限的情况,它更清晰。
Others have given the answer "for templating", but haven't really explained why. Curly braces are great for denoting blocks, but they kind of rely on indentation to be read clearly. So this is fairly clear:
It's obvious which brace matches which.
If, however, you're going into an HTML block, you're probably going to stop indenting cleanly. For instance:
That's hard to follow. If you use the
endif
style, it looks a little cleaner:The content of the code shows more clearly what's being done. For this limited case, it's more legible.
简短的回答:
始终使用
if($something) { }
并且几乎从不使用if/endif
。它从 PHP 4.0.0 起就成为标准,虽然旧语法并没有消失,但这是每个人都期望的语法。如果您确实正在寻找可以使用 if/endif 的情况,那么就是使用 php 作为模板语言时。
有些人喜欢这样的东西:
比
和恕我直言更好,因为每一行都会“说话”,当 php 标签之间有很多 html 时,这会很有帮助。
Short answer:
Always use
if($something) { }
and pretty much never useif/endif
. It's standard since PHP 4.0.0 and while the old syntax is not going away this is the one everybody expects.If you are really looking for a case where you can use if/endif then it's when using php as a template language.
Some people like something like this:
better than
and imho it is because every line "speaks" and that can be helpful when there is a lot of html inbetween the php tags.
两种方法都是可以接受的。有些人认为模板中的替代语法 (endif) 更清晰。恕我直言,由于现代语法着色/突出显示错误,这不再成立。只需选择一种风格并坚持下去即可。
Both methods are acceptable. Some people maintain that the alternative syntax (endif) is more legible in templates. IMHO, with a modern syntax coloring/highlighting error, that no longer holds true. Just pick a style and stick with it.
这是一种风格选择。它们是相似的,并且没有一个比另一个更好。
前者在某些情况下可能很好,因为当陷入 HTML 块集中间时可能更容易阅读。
It is a stylistic choice. They are analogous and one is not better than another.
The former can be good in certain circumstances because it may be easier to read when mired in the middle of an HTML block set.
我主要在停止和启动 php 代码块时使用 if/endif,因此几乎总是在输出原始 html 时使用。
例如:
至少在我看来,这看起来比以下更好:
I mostly use if/endif when stopping and starting the php code block in between, so nearly always when raw html is being outputted.
For example:
This looks, at least in my opinion, better than the following:
您可以使用两者,但首选样式和当前已知样式是标准
if(expr)
。You can use both, but preffered style and currently known style is the standard
if(expr)
.