你知道PHP的另一种语法吗,我孤陋寡闻了

最近在玩wordpress,发现其主题中的模板文件中经常出现一些带有冒号的“怪”语法。第一感觉这是 wordpress 本身定义的,类似于smarty这样的标签语法,从而需要先将其翻译成纯PHP代码,然后才能执行。很快发现我的想法是错误的!这种特殊语法与WordPress无关,而是PHP语言本身的特性!而且PHP手册中就有说明,只是本人孤陋寡闻了,实在是惭愧。今天把官文说明记录到这里,以备后用。

(1)基本规则,用:代替开始的{  ,用endif;等代替关闭的}。

(2)注意:这种替代语法不能和常规语法混用。

(3)这种替代语法的唯一目的是为了把PHP嵌入到html中时,使得代码整洁明了。


PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively. 




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


In the above example, the HTML block "A is equal to 5" is nested within an if statement written in the alternative syntax. The HTML block would be displayed only if $a is equal to 5. 

The alternative syntax applies to else and elseif as well. The following is an if structure with elseif and else in the alternative format: 




<?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;
?>  



Note: 

Mixing syntaxes in the same control block is not supported. 


Warning 
Any output (including whitespace) between a switch statement and the first case will result in a syntax error. For example, this is invalid: 




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

Whereas this is valid, as the trailing newline after the switch statement is considered part of the closing ?> and hence nothing is output between the switch and case: 




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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值