我爱编程

几点 PHP 小常识

2016-05-25  本文已影响53人  咚门

PHP 标记

当解析一个文件时,PHP 会寻找起始和结束标记,也就是 <?php 和 ?>,这告诉 PHP 开始和停止解析二者之间的代码。此种解析方式使得 PHP 可以被嵌入到各种不同的文档中去,因为任何起始和结束标记之外的部分都会被 PHP 解析器忽略。(由此可知,++PHP 本身其实是个模板语言++,这代表你可以在其他的语言中结合 PHP 使用,比如 HTML

如果文件内容是纯 PHP 代码最好在文件末尾删除 PHP 结束标记。这可以避免在 PHP 结束标签的后面 混入意料之外的空格或换行符,这些空格和换行符会导致多余的效果,因为 PHP 会输出缓存,而开发者并没有输出任何东西的意图。

<?php
echo "Hello world";

// ... more code

echo "Last statement";

// the script ends here with no PHP closing tag

从 HTML 中分离

凡是在一对开始和结束标记之外的内容都会被 PHP 解析器忽略,这使得 PHP 文件可以包含混合内容。 这可以让 PHP 嵌入到 HTML 文档中去,如下例所示。

<p>This is going to be ignored by PHP and displayed by the browser.</p>
<?php echo 'While this is going to be parsed.'; ?>
<p>This will also be ignored by PHP and displayed by the browser.</p>

示例:使用了条件的高级分离术(Advanced escaping using conditions)

<?php if ($expression == true): ?>
  This will show if the expression is true.
<?php else: ?>
  Otherwise this will show.
<?php endif; ?>

上例中, PHP 将跳过不符合条件的区块,即使它们位于 PHP 开始和结束标记之外。由于 PHP 解释器会在不符合条件时直接跳过该段条件语句块,因此 PHP 会根据条件来忽略之。

要输出大段文本时,跳出 PHP 解析模式 通常比 通过 echo 或 print 输出文本 更有效率

上一篇下一篇

猜你喜欢

热点阅读