Strange PHP syntax

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-10 12:38:37

问题


I've been working on PHP for some time but today when I saw this it came as new to me:

if(preg_match('/foo.*bar/','foo is a bar')):
        echo 'success ';
        echo 'foo comes before bar';

endif;

To my surprise it also runs without error. Can anyone enlighten me?

Thanks to all :)


回答1:


That style of syntax is more commonly used when embedding in HTML, especially for template/display logic. When embedded this way, it's a little easier to read than the curly braces syntax.

<div>
<? if ($condition): ?>
  <ul>
    <? foreach($foo as $bar): ?>
        <li><?= $bar ?></li>
    <? endforeach ?>
  </ul>
<? endif ?>
</div>

Versus:

<div>
<? if ($condition) { ?>
  <ul>
    <? foreach($foo as $bar) { ?>
      <li><?= $bar ?></li>
    <? } ?>
  </ul>
<? } ?>

The verbose end tags make it a little easier to keep track of nested code blocks, although it's still mostly personal preference.




回答2:


This is PHP's Alternative syntax for control structures.

Your snippet is equivalent to:

if(preg_match('/foo.*bar/','foo is a bar')) {
        echo 'success ';
        echo 'foo comes before bar';
}

In general:

if(cond):
...
...
endif;

is same as

if(cond) {
...
...
}



回答3:


http://php.net/manual/en/control-structures.alternative-syntax.php

Works for if, for, while, foreach, and switch. Can be quite handy for mixing PHP and HTML.




回答4:


You can read about it in Alternative syntax for control structures in the PHP manual. Reformatted, the code you posted looks like this:

if (preg_match('/foo.*bar/','foo is a bar')):
    echo 'success ';
    echo 'foo comes before bar';
endif;

This code is equivalent to:

if (preg_match('/foo.*bar/','foo is a bar')) {
    echo 'success ';
    echo 'foo comes before bar';
}

This syntax is available for several other control structures as well.

if ( condition ):
  // your if code
elseif ( other_condition ):
  // optional elseif code
else:
  // optional else code
endif;

while ( condition ):
  // your while code
endwhile;

for ( condition ):
  // your for code
endfor;

foreach ( condition ):
  // your foreach code
endforeach;

switch ( condition ):
  // your switch code
endswitch;



回答5:


It's the equivalent of:

if(preg_match('/foo.*bar/','foo is a bar')):
 echo 'success ';
 echo 'foo comes before bar';
endif;

which is equivalent to:

if(preg_match('/foo.*bar/','foo is a bar')){
    echo 'success ';
    echo 'foo comes before bar';
}

The wisdom of supporting non-standard conditional syntax is obviously questionable.



来源:https://stackoverflow.com/questions/2788891/strange-php-syntax

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