Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
658 views
in Technique[技术] by (71.8m points)

php - Is there harm in outputting html vs. using echo?

I have no idea really how to say this, but I can demonstrate it:

<?php
if (true) {
echo "<h1>Content Title</h1>";
}
?>

vs

<?php  if (true) {  ?>
<h1>Content Title</h1>
<?php  }  ?>

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. :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...