首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP/MySQL 三日通 (第 7 天):模板引入與程式碼模組化

     編輯:PHP 綜合知識

第三課起步:掌握 include()/require() 模組化代碼,奠定可維護架構基礎。

include() vs require()

特性require()include()
載入時機腳本啟動前(編譯階段)執行到該行時
條件判斷中無論條件真偽皆載入僅條件為真時載入
檔案不存在致命錯誤停止執行警告並繼續執行

建議:邏輯判斷區塊用 include(),核心配置檔用 require()。

安全性:副檔名 .inc 需設定解析

慣用 .inc 為模組副檔名,務必配置 Web 伺服器將 .inc 解析為 PHP,否則駭客可直接瀏覽原始碼(含資料庫密碼等敏感資訊)。

實戰:Header/Footer 模組化

header.inc

<?php
$db = mysql_connect("localhost", "root");
mysql_select_db("mydb", $db);
?>
<html><head><title><?php echo $title ?></title></head><body>
<center><h2><?php echo $title ?></h2></center>

footer.inc

</body></html>

主程式

<?php
$title = "Hello World";
include("header.inc");
$result = mysql_query("SELECT * FROM employees", $db);
echo "<table border=1>\n<tr><td>名字</td><td>職位</td></tr>\n";
while ($myrow = mysql_fetch_row($result)) {
    printf("<tr><td>%s %s</td><td>%s</td></tr>\n", $myrow[1], $myrow[2], $myrow[3]);
}
echo "</table>\n";
include("footer.inc");
?>

優勢

  • 主程式只需設定 $title,版頭版尾自動套用。
  • 資料庫連線集中管理,修改一處全站生效。
  • 結構清晰,配合函數與條件判斷可構建複雜應用。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved