當直接存取 $_GET[] 或 $_POST[] 且未先判斷鍵是否存在時,PHP 會拋出 Notice: Undefined index 警告。這不是 Bug,但會污染錯誤日誌。建議封裝安全取值函式:
/** 取代 $_GET 取值 */
function _get($key) {
return !empty($_GET[$key]) ? $_GET[$key] : null;
}
/** 取代 $_POST 取值 */
function _post($key) {
return !empty($_POST[$key]) ? $_POST[$key] : null;
}
/** 設定目前頁碼 */
$page = _get('page');
$inventory->setCurrentPage($page);
/** 取得表單參數 */
$sku = _post('sku');
$warehouse = _post('warehouse');
$supplier = _post('supplier');
此做法統一處理未定義索引情況,回傳 null 而非觸發警告,程式碼更乾淨且易於維護。實務上亦可擴充支援預設值、型別轉換、XSS 過濾等功能。