我正在通过一本书学习 PHP。作者使用echo
输出HTML。起初我认为这应该是这样做的,但后来我拿起了一本更“高级”的书。第二本书的作者在 HTML 之间插入了 PHP 代码,而不是回应整个事情。在从事大型项目的大型网络开发公司中,它是如何完成的?您可以使用其中之一,还是一个比另一个更容易被接受?
以这段代码为例:
<?php
//pagination
if ($pages > 1) {
//determine the current page
$current_page = ($start / $display) + 1;
//print out Previous Page button
if ($current_page != 1) {
?>
<div class="pages"><strong><a href="view_users.php?s=<?php echo ($start - $display); ?>&p=<?php echo $pages; ?>"> < </a></strong></div>
<?php
}
//print the page numbers
for ($i = 1; $i <= $pages; $i++) {
if ($i == $current_page) {
?>
<div class="pages active"><span> <?php echo $i; ?> </span></div>
<?php
}
else {
?>
<div class="pages"><strong><a href="view_users.php?s=<?php echo ($display * ($i - 1)); ?>&p=<?php echo $pages; ?>"> <?php echo $i; ?> </a></strong></div>
<?php
}//end of $i = $current_page conditional
}//end of FOR loop
if ($current_page < $pages) {
?>
<div class="pages"><strong><a href="view_users.php?s=<?php echo ($start + $display); ?>&p=<?php echo $pages; ?>"> > </a></strong></div>
<?php
}
}//end of pagination
include('includes/footer.php');
?>
这是正确的做法吗,还是我应该使用这样的方法:
echo '<a href="view_users.php?s=' . ($display * ($i - 1)) .
'&p=' . $pages . '&sort=' . $sort . '">' . $i . '</a> ';
我之所以这么问,是因为我发现使用第二种技术时很难正确对齐 HTML,而且我不想早早养成任何不良习惯。
最佳答案
第一种方法使您的代码更具可读性。当您需要打印少量 html 代码时,第二种方法很有用。您也可以使用简短的开放标签在 html 标签之间插入您的 php 代码。例如,如果您需要打印 URL 的语言参数,您可以这样做:
<a href="index.php?lang=<?=$lang?>" >A Link</a>
这等于:
<a href="index.php?lang=<?php echo $lang; ?>" >A Link</a>
关于php - 结合 PHP 和 HTML 的约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11220078/