略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: 流程控制的替代语法

2024-03-28

流程控制的替代语法

(PHP 4, PHP 5, PHP 7, PHP 8)

PHP 提供了一些流程控制的替代语法,包括 ifwhileforforeachswitch。替代语法的基本形式是把左花括号({)换成冒号(:),把右花括号(})分别换成 endif;endwhile;endfor;endforeach; 以及 endswitch;

<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>

在上面的例子中,HTML 内容“A is equal to 5”用替代语法嵌套在 if 语句中。该 HTML 的内容仅在 $a 等于 5 时显示。

替代语法同样可以用在 elseelseif 中。下面是一个包括 elseifelseif 结构用替代语法格式写的例子:

<?php
if ($a == 5):
    echo 
"a equals 5";
    echo 
"...";
elseif (
$a == 6):
    echo 
"a equals 6";
    echo 
"!!!";
else:
    echo 
"a is neither 5 nor 6";
endif;
?>

注意:

不支持在同一个控制块内混合使用两种语法。

警告

switch 和第一个 case 之间的任何输出(含空格)将导致语法错误。例如,这样是无效的:

<?php switch ($foo): ?>
    <?php case 1?>
    ...
<?php endswitch ?>

而这样是有效的,因为 switch 之后的换行符被认为是结束标记 ?> 的一部分,所以在 switchcase 之间不能有任何输出:

<?php switch ($foo): ?>
<?php 
case 1?>
    ...
<?php endswitch ?>

更多例子参见 whileforif

add a noteadd a note

User Contributed Notes 2 notes

up
0
toxyy
1 month ago
I feel compelled to give a more elegant way using heredoc than the other comment:

<ul>
<?php foreach($list as $item): echo
<<<ITEM
    <li id="itm-$item[number]">Item $item[name]</li>
ITEM;
endforeach;
?>
</ul>

Which works better with multi line blocks, as you only need one overall php tag.

(please don't omit the closing </li> tag despite it being legal, personal preference)
up
-18
johannes dot kingma at gmail dot com
7 months ago
The alternative control syntax can be combined elegantly with the short php notation <?- => for output where both blend in into the html code

    <ul>
    <?php for($counter=0; $counter<10; $counter++) :?>
        <li id="itm-<?=$counter?>">Item <?=$counter?>
    <?php endfor;?>
    </ul>

(Btw. ommiting the </li> is perfectly legal)

官方地址:https://www.php.net/manual/en/control-structures.alternative-syntax.php

冷却塔厂家 广告
-- 广告
北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3