簡體   English   中英

奇怪的PHP語法

[英]Strange PHP syntax

我已經在PHP上工作了一段時間,但今天當我看到它時,它對我來說是新的:

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

endif;

令我驚訝的是它也運行沒有錯誤。 任何人都可以開導我嗎?

謝謝大家 :)

這是PHP的控制結構替代語法

您的代碼段相當於:

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

一般來說:

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

和...一樣

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

嵌入HTML時更常用這種語法,尤其是模板/顯示邏輯。 以這種方式嵌入時,它比花括號語法更容易閱讀。

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

與:

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

詳細的結束標記使得跟蹤嵌套代碼塊變得更容易,盡管它仍然主要是個人偏好。

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

適用於ifforwhileforeachswitch 混合PHP和HTML非常方便。

您可以在PHP手冊中的控制結構的替代語法中閱讀它。 重新格式化,您發布的代碼如下所示:

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

此代碼相當於:

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

此語法也可用於其他幾種控制結構。

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;

它相當於:

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

這相當於:

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

支持非標准條件語法的智慧顯然是值得懷疑的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM