首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 常用類型判斷函數完整指南:is_array、is_int、is_string、is_object 等實戰用法

     編輯:PHP 綜合知識

為什麼需要類型判斷

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, NANis_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())); // 對象

進階技巧與最佳實踐

1. 嚴格類型聲明(PHP 7.0+)

declare(strict_types=1);
function sum(int $a, int $b): int {
    return $a + $b;
}
// sum('1', '2'); // TypeError,強制類型安全

2. 聯合類型與 mixed(PHP 8.0+)

function format(int|float|string $val): string {
    if (is_int($val)) return "整數:$val";
    if (is_float($val)) return "浮點:$val";
    return "字串:$val";
}

3. 避免常見陷阱

  • 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。
  • 資源類型在 PHP 8 許多擴展中已遷移為對象(如 GdImage, CurlHandle),is_resource() 將漸棄用。

4. 自定義類型守衛函數

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 弱類型環境下構建健壯、可維護的代碼。記住:永遠不要假設變量類型,使用前必須驗證。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved