输出 html 与使用 echo 有什么害处吗?
我真的不知道该怎么说,但我可以演示一下:
I have no idea really how to say this, but I can demonstrate it:
<?php
if (true) {
echo "<h1>Content Title</h1>";
}
?>
对
<?php if (true) { ?>
<h1>Content Title</h1>
<?php } ?>
两者之间有什么区别?不使用echo会不会出现问题?编写 echo "html 代码" 似乎超级乏味;一直以来,特别是对于较大的 html 片段.
What differences are there between the two? Will there be problems caused by not using echo? It just seems super tedious to write echo "html code"; all the time, specially for larger segments of html.
另外,对能够更好地改写我的问题的人表示感谢.:)
Also, bonus kudos to someone who can rephrase my question better. :)
推荐答案
这两种情况有一点区别:
There's a small difference between the two cases:
<?php
if (true) {
echo "<h1>Content Title</h1>";
}
?>
在这里,因为您使用的是 双引号 在您的字符串中,您可以插入变量并呈现它们的值.例如:
Here, because you're using double quotes in your string, you can insert variables and have their values rendered. For example:
<?php
$mytitle = 'foo';
if (true) {
echo "<h1>$mytitle</h1>";
}
?>
而在您的第二个示例中,您必须将 echo 包含在 php 块中:
Whereas in your second example, you'd have to have an echo enclosed in a php block:
<?php if (true) { ?>
<h1><?php echo 'My Title'; ?></h1>
<?php } ?>
就个人而言,我使用与第二个示例相同的格式,有点扭曲:
Personally, I use the same format as your second example, with a bit of a twist:
<?php if (true): ?>
<h1><?php echo $mytitle; ?></h1>
<?php endif; ?>
我发现它增加了可读性,尤其是当您有嵌套的控制语句时.
I find that it increases readability, especially when you have nested control statements.
相关文章