PHP 是弱類型語言,變量類型在運行時動態變化。在處理外部輸入、API 回調、數據庫結果、配置文件解析等場景時,必須在使用前確認變量類型,避免「對非數組調用 foreach」「對 null 調用方法」等致命錯誤。
| 函數 | 判斷目標 | 返回 true 示例 | 注意事項 |
|---|---|---|---|
is_array() | 數組 | [], ['a'=>1] | 最常用,[] 也算數組 |
is_bool() | 布爾值 | true, false | 僅這兩個值 |
is_int() / is_integer() / is_long() | 整數 | 123, -10 | 浮點數 1.0 返回 false |
is_float() / is_double() / is_real() | 浮點數 | 1.23, INF, NAN | is_double 別名 |
is_numeric() | 數字或數字字串 | 123, '123', '1.23', '0xFF' | 十六進制字串也算 |
is_string() | 字串 | '', 'abc' | 空字串也算 |
is_object() | 對象 | new StdClass() | 資源不是對象 |
is_resource() | 資源類型 | fopen(), mysqli_connect() | PHP 8+ 許多資源遷移為對象 |
is_scalar() | 標量類型 | int, float, string, bool | 不含 array, object, resource, null |
is_callable() | 可調用結構 | 'strlen', [$obj,'method'], fn()=>1 | 檢查回調有效性 |
is_iterable() | 可迭代 | array, Traversable 實現類 | PHP 7.1+ |
is_null() | null 值 | null | 未定義變量也會觸發 notice |
isset() | 變量存在且非 null | $a=1 | 語言結構,非函數,速度最快 |
empty() | 空值判斷 | '', 0, '0', null, false, [] | 語言結構,等同 !$var 但不報錯 |
<?php
// 1. 數組判斷
$colors = ['red', 'blue', 'green'];
if (is_array($colors)) {
echo "colors 是數組\n";
}
// 2. 整數判斷
$pageCount = 2234;
if (is_int($pageCount)) {
echo "$pageCount 是整數\n";
}
// 3. 浮點數判斷
$temperature = 15.23;
if (is_float($temperature)) { // 推薦 is_float,is_double 為別名
echo "temperature 是浮點數\n";
}
// 4. 對象判斷
class Widget {
public string $name;
public int $length;
}
$thing = new Widget();
if (is_object($thing)) {
echo "thing 是對象\n";
}
// 5. 字串判斷
$greeting = "Hello";
if (is_string($greeting)) {
echo "greeting 是字串\n";
}
// 6. 綜合驗證函數示例
function processData(mixed $input): string {
if (is_array($input)) {
return '收到數組,元素數:' . count($input);
} elseif (is_string($input)) {
return '收到字串,長度:' . strlen($input);
} elseif (is_int($input)) {
return '收到整數:' . $input;
} elseif (is_object($input)) {
return '收到對象,類:' . get_class($input);
} else {
return '未知類型:' . gettype($input);
}
}
var_dump(processData(['a', 'b'])); // 數組
var_dump(processData('hello')); // 字串
var_dump(processData(123)); // 整數
var_dump(processData(new Widget())); // 對象
declare(strict_types=1);
function sum(int $a, int $b): int {
return $a + $b;
}
// sum('1', '2'); // TypeError,強制類型安全
function format(int|float|string $val): string {
if (is_int($val)) return "整數:$val";
if (is_float($val)) return "浮點:$val";
return "字串:$val";
}
is_numeric(' 123 ') 返回 true,但 is_int('123') 返回 false。is_float(1.0) 返回 true,is_int(1.0) 返回 false(1.0 是 float)。isset($arr['key']) 比 array_key_exists('key', $arr) 快,但對 null 值鍵返回 false。is_resource() 將漸棄用。function assertArray(mixed $val, string $msg = '必須為數組'): array {
if (!is_array($val)) throw new InvalidArgumentException($msg);
return $val;
}
function assertString(mixed $val, string $msg = '必須為字串'): string {
if (!is_string($val)) throw new InvalidArgumentException($msg);
return $val;
}
// 使用
$items = assertArray($_POST['items'] ?? []);
$name = assertString($_POST['name'] ?? '');
熟練掌握 is_* 函數族,結合嚴格類型聲明、聯合類型、守衛函數,能在 PHP 弱類型環境下構建健壯、可維護的代碼。記住:永遠不要假設變量類型,使用前必須驗證。