最近在玩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 ?>