简体   繁体   中英

A lot of opening/closing of PHP tags

I've always wondered: does having a large open and close PHP (ie a template) hurt?

To clarify:

 <html>
    <?php echo $test; ?>
    <body <?php echo $test2; ?>>
    <table>
        <?php foreach ($rows as $row): ?>
        <tr>
            <td><?php echo $row['cell1']; ?></td>
            <td><?php echo $row['cell1']; ?></td>
            <td><?php echo $row['cell1']; ?></td>
            <td><?php echo $row['cell1']; ?></td>
            <?php echo $row['added cells']; ?>
        </tr>
        <?php endforeach; ?>
    </table>
    <?php echo $someMorePhp; ?>
    <div>
        <?php /*do some more php stuff */ ?>
    </div>
    etc etc
    etc

Or would it be advisable to ie

<html>
<php echo $test.'<body'.$test2; ?>>
<table>
    <?php foreach ($rows as $row) {
    echo '<tr>
        <td>'.$row['cell1'].'</td>
        <td>'.$row['cell2'].'</td>
        <td>'.$row['cell3'].'</td>
        <td>'.$row['cell4'].'</td>
        <td>'.$row['cell1'].'</td>
        '.$row['added cells'].'
    <tr>';
    }
</table>
// etc

I know this might seem like a micro optimization and such. To be clear i'm looking for a rule-of-thumb not a specific usecase... Will it hurt entering and exiting the php engine during a single script run...

No, that is no problem, you should always opt for better readability in this case.

Also think about either activating shorttags if possible (but beware, those might have some sideeffects / problems with XML sytnax as stated in the comments)

<? if ($bool) { ?>
    <?= $myVarThatIWantToOutput ?>
<? } ?>

Or think about using a template engine like smarty or twig, which restrict you somehow to force splitting of concerns, make some stuff easier (and more readable) and allow caching of compiled templates to make sure you still get the right speed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM