學習 PHP 不僅是會寫語法,更要掌握「PHP 的做事方式」。以下 10 個技巧助你寫出可維護、高效能的代碼。
採用 index.php?page=home 模式,透過單一入口控制頁面顯示,避免為每個頁面建立獨立檔案。
整合 $_GET、$_POST,簡化資料接收:$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 0;
var_dump() 能完整顯示變數型態與值,是追蹤資料流最直接的工具。
引入 Smarty 模板引擎,將 PHP 邏輯與 HTML 結構分離,利於團隊協作與維護。
避免到處宣告全域變數,將資料庫連線等共用設定集中在 config.php,減少耦合。
在 index.php 定義常數 define('yourPage',1);,其他頁面開頭檢查 if (!defined('yourPage')) die('Access Denied');,阻擋繞過入口的直接存取。
建立資料庫類別統一處理查詢、錯誤處理、審計日誌。範例:
- public function dbExec($query)
- {
- $result = $this->db->exec($query);
- if (PEAR::isError($result))
- errorRedirect($result->getMessage(), true);
- else
- return $result;
- }
搭配輸入過濾函數 sanitizeInput() 防止 SQL 注入。
PHP 檔案只負責接收輸入,實際邏輯委派給類別方法。利用 switch 分派動作:
- require_once PROJECTROOT.'libs/messages.class.php';
- $message = new Message();
- switch ($action)
- {
- case 'display':
- $message->display();
- break;
- ...
熟悉關聯查詢、別名等進階 SQL 技巧,所有用戶輸入必須經過過濾再用於查詢。
對於只需初始化一次的物件(如 Smarty),使用單例模式避免重複建立:
- function smartyObject()
- {
- if ($GLOBALS['config']['SmartyObj'] == 0)
- {
- $smarty = new SmartyGame();
- $GLOBALS['config']['SmartyObj'] = $smarty;
- }
- else
- $smarty = $GLOBALS['config']['SmartyObj'];
- return $smarty;
- }