萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 變數型別檢測與存在性判斷:gettype()、is_* 系列與 isset() 完整指南

PHP 是動態弱型別語言,變數型別由值決定且可隨時改變。準確判斷型別與存在性是撰寫健壯程式碼的基礎。本文系統整理 gettype()、is_* 系列函數與 isset() 的正確用法、效能差異與常見誤區。

型別檢測兩大流派

gettype():取得型別字串標籤

gettype(mixed $value): string

回傳值可能為:"boolean"、"integer"(非 "int")、"double"(非 "float")、"string"、"array"、"object"、"resource"、"NULL"、"unknown type"。

$vars = [
    true,
    42,
    3.14,
    'hello',
    [],
    new stdClass(),
    fopen('php://memory', 'r'),
    null,
];

foreach ($vars as $v) {
    echo gettype($v) . "\n";
}
// 輸出:boolean, integer, double, string, array, object, resource, NULL

⚠️ 官方不建議用於型別判斷邏輯

「不要使用 gettype() 來測試某種類型,因為其回傳的字串在未來版本中可能改變。此外,因為包含字串比較,執行速度較慢。請改用 is_* 函數。」

is_* 系列函數:型別判斷的標準方式

函數檢測型別回傳備註
is_bool()布林值bool
is_int() / is_integer() / is_long()整數bool不包含數值字串 "42"
is_float() / is_double() / is_real()浮點數bool
is_numeric()數值或數值字串bool"42", "3.14", "+0123" 皆為 true
is_string()字串bool
is_array()陣列bool
is_object()物件bool
is_resource()資源boolPHP 8.0+ 許多資源已改為物件
is_null()nullbool
is_scalar()純量型別boolint/float/string/bool,不含 array/object/resource/null
is_callable()可呼叫類型bool函數、閉包、實作 __invoke 的物件、類別方法陣列
is_iterable()可迭代boolPHP 7.1+,陣列或實作 Traversable
is_countable()可計數boolPHP 7.3+,陣列或實作 Countable

效能比較:is_* vs gettype()

$val = 'test';
$iterations = 1_000_000;

// is_string()
$t = microtime(true);
for ($i = 0; $i < $iterations; $i++) is_string($val);
echo "is_string: " . (microtime(true) - $t) . "s\n"; // ~0.03s

// gettype() === 'string'
$t = microtime(true);
for ($i = 0; $i < $iterations; $i++) gettype($val) === 'string';
echo "gettype===: " . (microtime(true) - $t) . "s\n"; // ~0.12s (慢 4 倍)

結論:is_* 系列為內部 C 函數直接判斷型別標記,無字串分配與比較開銷,效能顯著優於 gettype()。

存在性判斷:isset() 與相關函數

isset():變數是否「已宣告且非 null」

isset(mixed $var, mixed ...$vars): bool
  • 單一參數:變數存在且不為 null 回傳 true
  • 多參數:所有變數皆符合條件才回傳 true(短路求值)
  • 適用對象:變數、陣列元素、物件屬性(含魔術 __isset)
  • 不適用:函數回傳值、常數、運算式結果
$a = 'hello';
$b = null;
$c = []; // 未定義

isset($a);           // true
isset($b);           // false(值為 null)
isset($c);           // false(未定義)
isset($a, $b);       // false($b 為 null)
isset($arr['key']);  // 檢查陣列鍵是否存在且值非 null
isset($obj->prop);   // 檢查物件屬性,觸發 __isset()

empty():是否為「空值」

等價於 !isset($var) || !$var,但不會觸發「未定義變數」警告。

empty('');       // true
empty(0);        // true
empty('0');      // true ⚠️ 字串 "0" 視為空
empty(0.0);      // true
empty(null);     // true
empty([]);       // true
empty(false);    // true
empty('hello');  // false

array_key_exists():鍵是否存在(不檢查值)

$arr = ['key' => null];
isset($arr['key']);           // false(值為 null)
array_key_exists('key', $arr); // true(鍵存在)

property_exists():物件屬性是否宣告(不檢查值/可視性)

class A { private $p = null; }
$a = new A();
property_exists($a, 'p'); // true
isset($a->p);             // false(私有且為 null)

實戰決策樹:該用哪個?

  1. 要檢查變數/陣列鍵/物件屬性是否存在且非 null → isset()
  2. 要檢查變數/值是否為「空」(含 0、"0"、false、空陣列) → empty()
  3. 要檢查陣列鍵是否存在(值可為 null) → array_key_exists()
  4. 要檢查物件屬性是否宣告(含私有、靜態、值為 null) → property_exists()
  5. 要判斷具體資料型別 → is_int(), is_string(), is_array() 等
  6. 要取得型別名稱字串(除錯/日誌/序列化) → gettype() 或 get_debug_type() (PHP 8.0+)

PHP 8.0+ 新增:get_debug_type()

get_debug_type(mixed $value): string

比 gettype() 更精確、更符合型別宣告語法:

值gettype()get_debug_type()
42integerint
3.14doublefloat
[1,2]arrayarray
new Foo()objectFoo
fn() => 1objectClosure
fopen(...)resourceresource (stream)
nullNULLnull

除錯、日誌、例外訊息建議改用 get_debug_type()。

常見誤區總結

誤區正確認知
gettype($x) === 'integer' 判斷整數用 is_int($x),效能更好且語意明確
isset($func()) 檢查函數回傳語法錯誤,需先賦值給變數
empty($str) 判斷字串空白"0" 會被視為空,嚴格檢查用 $str === '' 或 trim($str) === ''
is_numeric("0xFF") 為 true十六進制字串視為數值,但 is_int("0xFF") 為 false
檢查 $_GET['id'] 用 isset($_GET['id'])正確,但若參數為空字串 ?id= 則為 true,值為 "",需再配合 !== ''

總結

  • 型別判斷:一律使用 is_* 系列,效能最好、語意最清晰、不受字串回傳值變更影響
  • 存在性判斷:isset() 為首選(檢查變數/鍵/屬性存在且非 null),empty() 判斷空值,array_key_exists() 區分「鍵存在但值為 null」
  • 除錯輸出:PHP 8.0+ 用 get_debug_type(),舊版用 gettype()
  • 嚴格型別模式:declare(strict_types=1) 可強制函數參數/回傳型別,減少執行期型別判斷需求
copyright © 萬盛學電腦網 all rights reserved