开发者

Print <<< END; question

Okay, so I have a question. I use print <<< END followed by an END; after my html and variables instead of echo and print. I use this because it doesn't s开发者_开发百科eem to have an effect on speed and the code just looks more organized in my opinion. I'm sure others will disagree but it's just my opinion.

I have a current project and that's the primary method I use to output HTML. No problems so far.

What are the disadvantages to using this? I have spoken with coders about it before, but they never really give me a reason not to use it just to not use it. I would appreciate any advice on this because I haven't had any problems with it.


The syntax you're describing is called a heredoc. As far as I know there is no performance difference between using heredocs and single- / double-quoted strings.

Heredocs can often help to prevent syntax errors, because there is no need to escape ' and " within the string. Another option would be to jump out of PHP into plain HTML, which requires no echo calls whatsoever:

<?php

... do things ...

?>
<div id="result"><?php var_dump($result); ?></div>
<?php

... do more things ...

?>


The only disadvantage i can think of is its harder to read for developers. This too is opinion but i find it much easier to read alternate syntax in template files, i.e.:

<?php if($something): ?>
  <div id="something">
    <?php echo $something->text ?>
  </div>
<?php endif; ?>

And switching in and out like this is the only reason i can see to use heredoc as far as html is concerned. IF you have functions that are outputting massive amounts of html then you should change those to include a file in some manner. IE. you shoudl need to switch in and out of html except in your view, and those views should be separate completely form your functions or models. for exampl you should be doing:

function getSomething($var){
  if($var){
   $html = <<< HTML
<div id="something">
  $var->text
</div>
HTML;
 }
}

This is obvioulsy a simle example and actually this example isnt so bad, but if the HTML is more complex it starts to get jsut ugly. And in the case of methods on model classes its just plain evil no matter how simple the HTML is. Id prefer something like the following:

getSomething($var, $template = 'something.php')
{
   if($var){
     ob_start();
     include($template); // $var is accessible in something.php
     return ob_get_clean();
   }

   return null;
}

Of course the include will result in slight a performance hit but thats where caching comes in :-)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜