为什么我们应该将PHP与HTML分开 [英] Why should we separate PHP from HTML
问题描述
我对编程颇为陌生,并且我知道如何将PHP从HTML中分离出来,但是我想知道在做这件事情时是否有任何区别:
<?php $ rand =我爱苹果?>
< h1>这是一个标题< / h1>
< div>
< p>这是一段< / p>
<?php echo变量包含字符串$ rand; ?>
< / div>
?>
与此相比:
<?php
echo< h1>这是一个标题< / h1>;
回声< div>;
echo< p>这是段落< / p>;
echo变量包含字符串$ rand;
回显< / div>;
?>
在性能等方面有什么区别,将PHP代码从HTML代码中分离出来,然后回显在PHP的整个页面?
最佳实践不是将PHP与HTML分开,最佳做法是标记中的单独逻辑。
重要的是编码风格。 正确的行缩进。使用 echo< / div>;
而不是 echo< / div>;
,有效的HTML ,不将变量放入引号:
echo变量包含字符串$ rand;
更好(为什么?请参阅下面的评论):
echo变量包含字符串,
$ rand,
:-);
只需改进代码,编写干净,可读,可维护的代码,整个项目就可以获得更高的质量和价值。想象一下你想改变文本,你必须添加或改变很多 echo
es。
I'm rather new to programming and i know how to separate PHP from HTML, but i would like to know if there is any difference in doing
this:
<?php $rand="I love apples" ?>
<h1>This is a title</h1>
<div>
<p>This is a paragraph</p>
<?php echo"The variable contains the string $rand"; ?>
</div>
?>
compared to doing this:
<?php
echo "<h1>This is a title</h1>";
echo "<div>";
echo "<p>This is a paragraph</p>";
echo "The variable contains the string $rand";
echo "</div>";
?>
Is there any difference between in performance etc, between splitting the PHP code from the HTML code and just echoing the whole page in php?
The best practice is not to seperate PHP from HTML, the best practice is to seperate logic from markup.
Also important is coding style. Proper line indentions. Using echo "</div>";
instead of echo"</div>";
, valid HTML, not putting variables into quotations:
echo "The variable contains the string $rand";
better (why? see my comment below):
echo "The variable contains the string ",
$rand,
" :-)";
Your whole project gains much quality and worthness just by improving the code, writing clean, readable, maintainable. Imagine you want to change the Text, you would have to add or change lots of echo
es.
Code Style Guides > Pear, PSR, Zend <
encourage developers to keep their code readable, valid and cross-browser compatible
这篇关于为什么我们应该将PHP与HTML分开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!