When, where & why should I use the “alternative syntax” for Control Structures?

随声附和 提交于 2019-12-22 04:37:16

问题


A simple PHP if / else condition looks like this:

if(true) {
  echo("Hello World!");
} else {
  echo("Goodbye World!");
}

The "alternative syntax" looks like this:

if(true):
  echo("Hello World!");
else:
  echo("Goodbye World!");
endif;

I have a few questions regarding this "alternative syntax":

  1. When / in what case should I use it?
  2. Where / in which part of my script should I use it?
  3. Why should I use it / what purpose does it serve & are there any benefits to using it?
  4. Why was it created, does the "alternative syntax" have features that "original syntax" doesn't?

Thank you for you time & help in advance.


回答1:


I typically only use it when mixing HTML and PHP, so just for the sake of argument, here is an example to compare

<?php foreach( $vars as $var ): ?>
    <?php if($var):?>
      <p>Hello World!</p>
    <?php else:?>
      <p>Goodbye World!</p>
    <?php endif;?>
<?php endforeach; ?>


<?php foreach( $vars as $var ){ ?>
    <?php if($var){ ?>
      <p>Hello World!</p>
    <?php }else{ ?>
      <p>Goodbye World!</p>
    <?php } ?>
<?php } ?>

Granted this is small but if you extend this out about 800 lines it can get tricky to keep track of all those } having the endif; endforeach etc.. gives you just a bit better way to match the code blocks up when mixed with all the HTML content.

Again, I rarely use mixed HTML/PHP and I'd suggest using a Template engine if you have more then a few lines to do that mix the two. Because even this can wind up messy once you have a dozen endif; it loses it's point.

But, I guess in short I tend to think of it as a default template syntax...



来源:https://stackoverflow.com/questions/37819105/when-where-why-should-i-use-the-alternative-syntax-for-control-structures

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!