PHP 8.1 起傳 null 給 strlen、trim 會跳 Deprecated:為什麼你可能看不到

strlen(null)、trim(null)、htmlspecialchars(null) 在 PHP 8.1 起都是 Deprecated,PHP 9 預計變成錯誤。但 Ubuntu 預設的 php.ini 把 Deprecated 藏起來了,升級前要先打開才看得到。

從表單或網址參數取值,沒帶參數時常常是 null,接著直接丟給 trim()、strlen()。這在 PHP 8.1 起會產生 Deprecated 訊息,PHP 9 預計直接變成 TypeError。

重現

<?php
error_reporting(E_ALL);
$name = $_GET['name'] ?? null;      // 沒帶參數時是 null

echo strlen($name), "\n";
echo trim($name), "|\n";
echo htmlspecialchars($name), "|\n";
echo str_replace('a', 'b', $name), "|\n";
var_dump(str_contains($name, 'x'));

PHP 8.5.4 的輸出:

PHP Deprecated:  strlen(): Passing null to parameter #1 ($string) of type string is deprecated in null.php on line 5
0
PHP Deprecated:  trim(): Passing null to parameter #1 ($string) of type string is deprecated in null.php on line 6
|
PHP Deprecated:  htmlspecialchars(): Passing null to parameter #1 ($string) of type string is deprecated in null.php on line 7
|
PHP Deprecated:  str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated in null.php on line 8
|
PHP Deprecated:  str_contains(): Passing null to parameter #1 ($haystack) of type string is deprecated in null.php on line 9
bool(false)

程式還是照常執行,null 被當成空字串。只是每次呼叫都多一則 Deprecated。

為什麼要改

自己寫的函式,參數型別是 string 卻傳入 null,早就會丟 TypeError:

function shout(string $s): string { return strtoupper($s); }
shout(null);
TypeError: shout(): Argument #1 ($s) must be of type string, null given

內建函式過去對 null 比較寬鬆。PHP 8.1 開始讓內建函式和自訂函式的規則一致,先用 Deprecated 給大家改程式的時間。

你可能看不到這些訊息

上面的範例特地寫了 error_reporting(E_ALL)。拿掉那行,在 Ubuntu 的 PHP 8.5 上執行,一則 Deprecated 都不會出現。原因是套件附的 php.ini:

$ grep -n "^error_reporting" /etc/php/8.5/cli/php.ini /etc/php/8.5/fpm/php.ini
/etc/php/8.5/fpm/php.ini:483:error_reporting = E_ALL & ~E_DEPRECATED
/etc/php/8.5/cli/php.ini:483:error_reporting = E_ALL & ~E_DEPRECATED

~E_DEPRECATED 把所有 Deprecated 排除掉了。正式環境這樣設合理,但升級前不打開,就不知道哪些程式在 PHP 9 會壞掉。

開發或測試環境打開的方式:

php -d error_reporting=E_ALL script.php

或在開發環境的 php.ini 設成 error_reporting = E_ALL,並把 log_errors 打開,讓訊息寫進記錄檔。

修法

依情境選一種:

// 取值時就給預設值
$name = $_GET['name'] ?? '';

// 呼叫時補預設值
echo strlen($maybe ?? '');

// 明確轉型
echo htmlspecialchars((string) $maybe);

// 函式本身允許 null,就在型別上寫清楚
function greet(?string $name): string {
    return 'Hi ' . ($name ?? 'guest');
}
0
0
|
Hi guest

?? '' 和 (string) 的差別:(string) 也會把數字、物件(有 __toString)轉成字串;?? '' 只處理 null,其他型別錯誤照樣會被抓到。不確定時用 ?? ''。

大量舊程式怎麼找

  • Rector 有現成規則,可以自動在呼叫處補上 ?? '' 或轉型。
  • PHPStan 等靜態分析工具在較嚴格的檢查等級下,會標出可能傳入 null 的呼叫。
  • 最直接的方式:在測試環境打開 E_ALL,跑一遍測試或實際操作網站,看記錄檔裡的 Deprecated。

關於作者

已發表 274 篇文章

留言

還沒有留言。有補充、疑問或不同做法,歡迎第一個留言。

發表留言

Email 不會公開,只用於回覆通知。

第一次留言需經審核,之後會直接顯示。