0

I've always wondered: does having a large open and close PHP (i.e. 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 i.e.

<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...

4

1 回答 1

0

不,这没问题,在这种情况下,您应该始终选择更好的可读性。

如果可能,还要考虑激活短标签(但请注意,这些可能会对 XML sytnax 产生一些副作用/问题,如评论中所述)

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

或者考虑使用像 smarty 或 twig 这样的模板引擎,它会以某种方式限制你强制拆分关注点,使一些东西更容易(并且更具可读性)并允许缓存已编译的模板以确保你仍然获得正确的速度。

于 2013-11-15T11:04:31.853 回答