开发者

Does it make a difference if I put a bunch code inside a single php tag vs breaking it up?

Besides personal preference, does it make any difference?

<?php
  $meta = get_post_meta开发者_C百科(get_the_ID(), 'rw_strNum', true); 
  '' != $meta and print "$meta";
?>
<?php
  $meta = get_post_meta(get_the_ID(), 'rw_strName', true); 
  '' != $meta and print "$meta";
?>

as opposed to this

<?php
  $meta = get_post_meta(get_the_ID(), 'rw_strNum', true); 
  '' != $meta and print "$meta";

  $meta = get_post_meta(get_the_ID(), 'rw_strName', true); 
  '' != $meta and print "$meta";
?>


The first version will output an extra newline character into the generated output, since there's one between the ?> and the <?php:

?>
<?php

That is the only difference; there isn't any noticeable performance impact between the two.


Everything outside <?php ?> is treated as output. This means, that

?>
<?php

may output something. "May" because the newline after ?> is part of the tag and therefore not returned. But with something like

?>
  <?php

there are two whitespace echoed. The problem is, that you cannot set any headers anymore, after something is returned to the browser.


Like knittl said, it will not make any visible difference. The only difference is it will make your HTML easier to read when you mix PHP and HTML together, for example when doing templates.

The php parser goes through the whole file regardless and I doubt encountering a closing tag and then an opening tag has any impact on parsing/speed of parsing.


Yes it makes a difference. Look at this:

<?php
$uselessvar = 1;
?>
<?php
header('Location: /'); // This will not work
?>

<?php
$uselessvar = 1;
header('Location: /'); // This will work
?>

In the first example, there is a new line between the first closing tag ?> and the second opening tag <?php. This new line is treated as an output and it's send to the client. header function could not work if any output is sent to the client before its called. That's why the first example will not work where the second will.

In a more general way, it's better to use the closing tag ?> only where you need it, to avoid such errors. For example, you don't have to put a closing tag ?> at the end of a php file. Sometimes we see a file terminated by a closing tag then a new empty line. This new empty line has the same effect as above, and can crash/alter any script.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜