加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – if和else语句中“:”的用法是什么?

发布时间:2020-12-13 22:07:34 所属栏目:PHP教程 来源:网络整理
导读:我看到了以下代码片段: ?phpif(!empty($_POST)): // case I: what is the usage of the :if(isset($_POST['num']) $_POST['num'] != ''):$num = (int)$_POST['num'];....if($rows == 0):echo 'No';else: // case II: what is usage of :echo $rows.'Yes';en
我看到了以下代码片段:

<?php
if(!empty($_POST)): // case I: what is the usage of the :
if(isset($_POST['num']) && $_POST['num'] != ''):

$num = (int)$_POST['num'];

....

if($rows == 0):
echo 'No';

else: // case II: what is usage of :
echo $rows.'Yes';

endif;

我想知道php代码中“:”的用法是什么.

解决方法

这是 alternative syntax for control structures.

所以

if(condition):
    // code here...
else:
    // code here...
endif;

相当于

if(condition) {
    // code here...
} else {
    // code here...
}

在处理HTML时,这非常方便. Imho,它更容易阅读,因为你不必寻找大括号{}和PHP代码和HTML感觉不喜欢混淆.例:

<?php if(somehting): ?>

    <span>Foo</span>

<?php else: ?>

    <span>Bar</span>

<?php endif; ?>

我不会在“普通”PHP代码中使用替代语法,因为这里的大括号提供了更好的可读性.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读