Jos*_*eph 10 php syntax if-statement control-structure alternate
我已经工作PHP了一段时间,但今天当我看到它时,它对我来说是新的:
if(preg_match('/foo.*bar/','foo is a bar')):
echo 'success ';
echo 'foo comes before bar';
endif;
Run Code Online (Sandbox Code Playgroud)
令我惊讶的是它也运行没有错误.任何人都可以开导我吗?
谢谢大家 :)
cod*_*ict 28
您的代码段相当于:
if(preg_match('/foo.*bar/','foo is a bar')) {
echo 'success ';
echo 'foo comes before bar';
}
Run Code Online (Sandbox Code Playgroud)
一般来说:
if(cond):
...
...
endif;
Run Code Online (Sandbox Code Playgroud)
和...一样
if(cond) {
...
...
}
Run Code Online (Sandbox Code Playgroud)
Har*_*83- 14
嵌入HTML时更常用这种语法,尤其是模板/显示逻辑.以这种方式嵌入时,它比花括号语法更容易阅读.
<div>
<? if ($condition): ?>
<ul>
<? foreach($foo as $bar): ?>
<li><?= $bar ?></li>
<? endforeach ?>
</ul>
<? endif ?>
</div>
Run Code Online (Sandbox Code Playgroud)
与:
<div>
<? if ($condition) { ?>
<ul>
<? foreach($foo as $bar) { ?>
<li><?= $bar ?></li>
<? } ?>
</ul>
<? } ?>
Run Code Online (Sandbox Code Playgroud)
详细的结束标记使得跟踪嵌套代码块变得更容易,尽管它仍然主要是个人偏好.
http://php.net/manual/en/control-structures.alternative-syntax.php
适用于if,for,while,foreach,和switch.混合PHP和HTML非常方便.