function find(string $id, array $options = null) { ... }
型別寫的是 array,預設值卻是 null。PHP 過去會自動把它當成 ?array。PHP 8.4 起,這種「隱含可為 null」的寫法變成 Deprecated。
重現
[!NOTE]
> Ubuntu 套件預設的 php.ini 是 `error_reporting = E_ALL & ~E_DEPRECATED`,不加 `-d error_reporting=E_ALL` 看不到這些訊息。
## 修法
在型別前面加 `?`,或寫成聯合型別:
```php
function find(string $id, ?array $options = null) { ... }
class Repo {
public function save(object $entity, ?Logger $logger = null) {}
}
function both(string $id, int|string|null $key = null) {}
$ php -d error_reporting=E_ALL fixed.php
loaded
mixed、?int、int|null 本來就包含 null,不會觸發:
function m(mixed $x = null) {}
function n(?int $x = null) {}
function u(int|null $x = null) {}
mixed / ?int / int|null: no deprecation
為什麼要改
string $x = null 讓人誤以為型別是 string,實際上卻接受 null。呼叫端看函式簽章,不會知道要處理 null 的情況;函式內部也常忘了檢查。寫成 ?string,型別和實際行為一致。
對套件作者的影響
? 語法從 PHP 7.1 就有了,改成 ?string $x = null 不會影響對舊版 PHP 的支援,可以放心直接改。
因為訊息在載入檔案時就出現,使用你套件的人只要開了 E_ALL,記錄檔就會被這些 Deprecated 灌滿,即使他們根本沒用到那些函式。
一次改完
- PHP-CS-Fixer 的
nullable_type_declaration_for_default_null_value規則可以自動加上?。 - Rector 也有對應的規則。
- 手動找:
grep -rnE '\b[A-Za-z_\\]+ \$[a-zA-Z_]+ = null' src/,再排除已經有?或|null的結果。
發表留言