<?php
echo empty(strlen('test'));
// Fatal error: Can't use function return value in write context
?>
empty() 只接受變量PHP 官方文檔明確註明:
empty()only checks variables as anything else will result in a parse error. In other words, the following will not work:empty(trim($name)).
本質:empty() 是語言構造,而非函數。它的操作數**必須是變量**,以便在「未定義」時不拋錯誤直接返回 true。若傳入表達式/函數調用結果,編譯器無法解析為可寫入的變量槽位,導致編譯期致命錯誤。
empty(func()) 直接 **Fatal error**(編譯期)。empty(expr) 表達式,**但僅限於某些內建函數/語言構造**,用戶自定義函數仍報錯。<?php
// 錯誤
// empty(strlen('test'))
// 正確
$len = strlen('test');
if (empty($len)) { ... }
// 或直接邏輯判斷(更語義清晰)
$len = strlen('test');
if ($len === 0) { ... }
// 封裝為可復用函數(若極度需要 inline)
function isEmptyValue($value): bool {
return empty($value);
}
if (isEmptyValue(strlen('test'))) { ... } // 合法:傳入變量 $value
?>
empty() 判定為「空」的值| 值 | empty() | 備註 |
|---|---|---|
"" (空字符串) | true | |
0 (整數) | true | 常見坑:ID=0 會被視為空 |
"0" (字符串) | true | 字符串 "0" 也視為空 |
0.0 | true | |
null | true | |
false | true | |
[] (空數組) | true | |
| 未定義變量 | true | 不拋 Notice,這是 empty 存在的意義 |
"0.0" | false | 非空字符串 |
[0] | false | 非空數組 |
<?php
// 檢查變量是否「未設置或為 null」
isset($var) // 等價 !empty($var) 但不包含 0/"0"/false/[] 判定
// 檢查字符串是否非空(長度>0)
$str !== ''
// 檢查數組是否非空
!empty($arr) // 或 count($arr) > 0
// 檢查對象屬性/數組鍵是否存在且非 null
isset($obj->prop) / isset($arr['key'])
// 組合:存在且非空字符串
!empty($str) && $str !== '0' // 視業務決定是否排除 "0"
?>
empty() **只能直接作用於變量**,不能作用於函數調用、方法調用、表達式結果。Can't use function return value in write context 即由此引起。empty($var);或改用明確的比較運算符(=== null、=== ''、=== 0、=== false)。empty() 的「空」定義(含 0、"0"、false、[]),避免業務邏輯誤判(如 ID=0 被視為未設置)。