Should I wrap the whole thing inside <?php ?> using PHP?
Is there any difference between the following 2?
1 separate php code from html
<html> <body> <?php // php code 1 ... ?> <div> ... </div> <?php // php code 2 ... ?> <div> ... </div> <?php // php code 3 ... ?> </body> </html>
2 everything inside php
<?php echo "<html>"; ehco "<body>"; // php code 1 ... echo "<div> ... </div>"; // php code 2 ... echo "<div开发者_如何学JAVA> ... </div>"; // php code 3 ... echo "</body>"; echo "</html>"; ?>
Which is faster?
It is not the way to increase the speed. If you are not satisfied with your app performance - take profiler and find the slowest part. After that - optimize that slowest part.
The way "I optimize the things that it is easy to optimize" is always the worst.
The first one is faster because interpreter will take care only about the code inside the tags.
The second one should not be use, double quotes are interpreted to see if there is a variable inside. You should always use simple quote when you don't want string to be interpreted.
The usual usage is what you listed in the first form, although in some cases, such as a helper function to generate <a href="..." ... >link word</a>
, then you will generate HTML inside PHP code. Or if you have a function that generates a table, or an ul
with many li
printed out with data from inside an array or hash.
Whatever performance difference you'll find is moot and academic. Choose the first form. The second form isn't future-proof. A simple change in the layout of the HTML page will require a software engineer. The first will just require a creative designer.
With an opcode cache installed on the server (see: APC, eAccelerator), it doesn't matter either way, as the page only has to be interpreted the first time it's accessed.
Performance:
Perhaps the 2nd example would be slightly slower because it does more function calls & also when a string is inside double quotes then the interpreter will look for variables to substitute and escape sequences, eg. \n
PHP blocks also need to be parsed. This may be irrelevant is your script is pre-compiled / running on an accelerator.
Formatting:
1st example will produce HTML code automatically formatted with indentation. The 2nd example will produce code that's all on one line. Not really an issue as this can be corrected.
Readability:
Perhaps the first example is more readable. Eg. IDE can highlight syntax for HTML and separately for PHP
Others:
2nd example would probably be more preferred choice if the code is in a framework and markup gets extracted in to smaller function(s), sub-classed, etc?
精彩评论