我應該更喜歡其中一個片段,爲什麼?響應HTML代碼與將其從PHP中刪除
1.
function render()
{
echo "<div>$content</div>";
}
2.
function render()
{
?>
<div><?= $content ?></div>
<?php
}
我應該更喜歡其中一個片段,爲什麼?響應HTML代碼與將其從PHP中刪除
1.
function render()
{
echo "<div>$content</div>";
}
2.
function render()
{
?>
<div><?= $content ?></div>
<?php
}
兩者都不是一個好主意。 原因功能是輸出。設法讓這種方式:
function render($content_, $style_)
{
$res = "<div{$style_}>$content_</div>";
return $res;
}
...
然後:
echo render("Content inside div", " style='color:red;'")
原因:
作爲一般規則,最好讓組成應用程序的每個文件的內容儘可能整潔。由於PHP是一種模板語言,您可以擁有截然不同目的的PHP文件(認爲包含純HTML的文件是一個有效的PHP文件),我的個人偏好是:
如果您需要創建一小段代碼中的HTML,請勿打開和關閉PHP標記。
例如,喜歡這樣的:
function render()
{
echo "<div>$content</div>";
}
在此:
function render()
{
?><div><?= $content ?></div><?php
}
還觀察到,在片段上方我已經不只是PHP結束標記之前或之後所包含的任何空格PHP開放標籤;通常空白不是HTML顯著但它可以在兩種情況下重要:
如果您想在HTML中包含這種空格,那麼在任何情況下您的源代碼都會有點醜陋,但絕對是醜陋的如果你使用close/open標籤方法。
隔離視圖中的大塊HTML,並根據需要包含一小部分邏輯。
例如,喜歡這個:
<body>
<div id="blah">
<ul id="nav">
<?php foreach ($navItems as $url => $title) : ?>
<!--
NOTE:
You can opt to make the line below a single echo statement
in PHP rather than HTML with values from PHP substituted
in various places inside, and in this example it might even
be better. However, if the output for each item is more complex
than a li/a pair, it will be far more readable in this form.
-->
<li><a href="<?php echo $url ?>"><?php echo $title ?></a></li>
<?php endforeach; ?>
在這個:
$output = '<body><div id="blah"><ul id="nav">';
foreach ($navItems as $url => $title) {
$output .= '<li><a href="'.$url.'">'.$title.'</a></li>
}
echo $output;
考慮的問題包括文件或只是XPHP。所以基本上我們現在有4個選項:) – dragonjet 2011-05-07 11:29:38
您提出的選項的好處是什麼? – 2011-05-07 11:31:14
在這個設置中,我更喜歡第一個(只是爲了更清晰的代碼)。將PHP完全留在你的PHP代碼中更好,例如使用templateParser而不是'echo「