PHP : Better way to print html in if-else conditions
https://softwareengineering.stackexchange.com/questions/357782
-
20-01-2021 - |
문제
Please refer the following two forms of the same code
First:
<?php if(some_condition){
?>
<li><a target="_blank" href="example.com/channel1/" class="xyz">If content</a></li>
<?php
}else{
?>
<li><a target="_blank" href="example.com/channel2/" class="xyz">Else Content</a></li>
<?php?>
}?>
Second :
<?php
if(some_condition){
echo '<li><a target="_blank" href="example.com/channel1/" class="xyz">If content</a></li>';
}
else{
echo '<li><a target="_blank" href="example.com/channel2/" class="xyz">Else Content</a></li>';
}
?>
My question is which one of the following is a better option.I know the second one is more readable. But if there are so many conditions on the same page, then which is better performance-wise(i believe, there will be only a negligible performance difference between the two).
I would like to know your views/points, regarding standards performance and whatever you think I should know, about the two different forms.
(And which should be preferred over the other,when there is only single if-else block, and multiple if-else blocks)
Thanks
해결책
I would argue that the first example is the better of the two evils as it is more maintainable. The HTML is written as is, and not coded as a string literal.
Using templating or some other way to keep business logic and HTML presentation separate usually results in more maintainable code.
다른 팁
As always, the short and probably most correct answer: It depends.
To expand:
For the two snippets in that short as shown in the question it's purely about taste. There is no strong technical reason for one over the other. In a larger context the question is "are those rather HTML templates with a little logic in between or are those code parts with lot's of logic and a little of HTML?"
Of course if it's mostly logic, a good idea is to look into template library's like Twig or others and separate the logic from output in a larger degree, whcih allows testing and changing output formats more easily.