對照表
| 檢查對象 | 函數 | 參數 | 回傳 | 備註 |
| 常數 | defined() | 字串常數名 | bool | 需加引號 defined('CONST') |
| 變數 | isset() | 變數 | bool | 未宣告或 null 均回傳 false |
| 函數 | function_exists() | 字串函數名 | bool | 需加引號,含內建/擴展/使用者函數 |
| 類別 | class_exists() | 字串類別名 | bool | 可觸發自動載入 |
| 介面 | interface_exists() | 字串介面名 | bool | 同上 |
| Trait | trait_exists() | 字串 Trait 名 | bool | 同上 |
| 擴展 | extension_loaded() | 字串擴展名 | bool | 如 pdo_mysql |
| 輸入變數 | filter_has_var() | 類型常數, 名稱 | bool | 類型:INPUT_GET/POST/COOKIE/SERVER/ENV |
程式碼範例
<?php
// 常數
if (defined('MY_CONST')) echo MY_CONST;
// 變數
if (isset($var)) echo "變數存在: $var";
// 函數
if (function_exists('json_encode')) {
echo json_encode(['ok' => true]);
}
// 類別(觸發 autoload)
if (class_exists('PDO')) {
$pdo = new PDO('sqlite::memory:');
}
// 輸入變數
if (filter_has_var(INPUT_GET, 'id')) {
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
}
?>
常見誤區
isset($arr['key']) 檢查陣列鍵是否存在且非 null;若需區分「鍵存在但值為 null」,用 array_key_exists('key', $arr)。
function_exists 不區分大小寫(PHP 函數名大小寫不敏感)。
filter_has_var 僅檢查輸入來源是否存在,不代表通過驗證;驗證請用 filter_input()。
效能提示
- 以上函數皆為 O(1) 雜湊查找,效能極高。
- 避免在迴圈中重複呼叫
function_exists 判斷擴展是否載入,啟動時檢查一次快取結果。