Very simple question, requiring a very simple answer.
If I’ve got some PHP files that need to output a decent amount of html with variables, is it considering better to use echo/printf or is it better to end the php and start it up again?
ex:
<?php
$varA = 'foo';
$varB = 'bar';
?>
<span><?php echo $foo; ?></span>
<div><?php echo 'content ' . $bar; ?></div>
<?php
//continue php here
?>
is that considered better than
<?php
$varA = 'foo';
$varB = 'bar';
printf('<span> . $foo . </span>');
printf('<div>content ' . $bar . '</div>');
//continue php here
?>
or is the latter considered “better”, OR is one even considered better than the other, period!?
Thanks!
The answer here is fairly subjective, so my opinion is that the first approach is cleaner and easier to read, due mainly to the fact that if you happen to be working with a team who’s attempting to exercise some separation of concerns, then the front-end developer will have an easier time spotting the HTML tags if they themselves are not
echo‘d out by PHP (They may not even know PHP). Most text editors will not provide the pretty syntax highlighting for the HTML if it is wrapped in a PHP string.It might also be noted that if you are working in a strict MVC environment, then your views should contain as little PHP as possible, and should really just be a bunch of
echos. I think the first approach lends itself towards providing a more HTML look and feel, if you will.As @hyphen-this has stated, heredoc syntax is also an accepted route, and removes the need for jumping in and out of PHP mode.