开发者

Preferred formatting for this / best practice?

开发者 https://www.devze.com 2023-01-08 04:15 出处:网络
Suppose I want to create a select box in PHP. $months = array (\'Jan\',\'Feb\',\'Mar\',\'Apr\',\'May\',\'Jun\',\'Jul\',\'Aug\',\'Sep\',\'Oct\',\'Nov\',\'Dec\');

Suppose I want to create a select box in PHP.

$months = array ('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');

Option 1:

<select name="month">
    <option value="">Month</option>
    <option value="">-------</option>
    <?php foreach ($months as $monthNum => $month) { ?>
    <option value="<?php echo $monthNum+1 ?>"><?php echo $month ?></option>
    <?php } ?>
</select>

Option 2:

<select name="month">
    <option value="">Month</option>
    <option value="">-------</option>
    <?php 
        foreach (months() as $monthNum => $month) 
            echo '<option value="' . ($monthNum+1) . '">' . $month . "</option>\n"; 
?>
</select>

I personally think Option 1 renders the code harder to read and understand, at the same time Option 2 screws the indentation and puts more HTML into PHP.

Which option is preferred?

EDIT: I don't want to add another template engine on top of PHP, which is i开发者_运维百科tself a template engine.


I think the second option is better because things like <option value="<?php echo $monthNum+1 ?>"> simply are hard to read and understand and imho even a little bit illogical (a tag in a tag.)

But honestly, use what you like more. Only one suggestions: Maybe instead of using <?php foreach () { ?> ... <?php } ?> which is sometimes hard to understand you may use this syntax: <?php foreach (): ?> ... <?php endforeach; ?>. Especially if you start having foreaches in fors in whiles in foreaches in fors this syntax may be a little bit easier to understand.


Option 2 no doubt, is semantic where is php is php where is html is html


I'd go for a) what ever is easier to maintain for you and your colleagues and b) consistency.

If you (and your colleagues) think that 1 is harder to read and understand then don't use it. In 6/12/18 months time when you come back to the code it will be even harder to understand than it is now.


Personally, I use Option 1, because I consider it a supreme priority to keep HTML and PHP code as separate as possible.

If it helps, I often use the shorthand <?= 'value'; ?> instead of <?php echo 'value'; ?>.


I think option 1 is perfectly fine to read. However, if you do not like the lonely } at the end, you could use php's alternativ syntax (using endforeach).


In my opinion option 2 reads like a script that spits out some strings, where option 1 reads like an HTML template with embedded PHP code. For view templates in an MVC framework, I find that option 1 is the best looking and easiest to read. For CLI or other purposes, option 2 works better.

0

精彩评论

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