6

就 Web 服务器的 CPU 优化而言,哪个更好?编写纯 HTML 并在这里和那里插入 PHP 代码?

<script type="text/javascript">$(document).ready(function(){$('#search').focus();});</script>
<div id="default">
    <div class="left">
        <?include(DIR_DIV.'facebook.php')?>
    </div>
    <div class="right">
        <?include(DIR_ADS.'google.300x250.php')?>
    </div>
    <div class="sep"></div>
</div>

或者在 PHP 中使用 echo 编写所有 HTML?

echo '<script type="text/javascript">$(document).ready(function(){$(\'#search\').focus();});</script>';
echo '<div id="default">';
    echo '<div class="left">';
        include(DIR_ADS.'google.300x250.php');
    echo '</div>';
    echo '<div class="right">';
        include(DIR_DIV.'facebook.php');
    echo '</div>';
    echo '<div class="sep"></div>';
echo '</div>'

差异甚至重要还是微不足道?

4

4 回答 4

13

最后,差异是否重要还是微不足道?

性能方面并不重要,它完全无关紧要。

不过,可读性确实很重要——我发现第一个块第二个块更清晰。像这样将 HTML 包装到 PHP 代码中是没有意义的——一方面,调试变得更加困难。

于 2011-12-02T18:33:07.497 回答
2

第一个块可以称为 php 模板,第二个是纯 PHP。

It really depends on what you will be writing more. If HTML - use first, if PHP still use first, just separate it to different file and use as template :)

于 2011-12-02T18:36:45.023 回答
1

If you were writing an entire page (and a complex one) with echo you may add a little bit of overhead, since all those lines would need to be executed server side.

I try to stay away from that for the readability issue mentioned in the other answer, though there may be cases (like having to branch based on some values) where you may need to use this approach.

于 2011-12-02T18:37:32.877 回答
1

There is really no difference between the two when it comes to how the server will see it. It all comes down to how easy it would be to update it. you can have issues with single and double quotes because you would need to make sure to escape the same type of quotes that you are using to contain the html. like

echo " <span class=\"first\">".$first."</span>";

This can be a pain some times in long pages.

于 2011-12-02T19:23:35.700 回答