PHP 8.4 Deprecated:string $x = null 要改成 ?string $x = null

參數型別寫 string、預設值給 null,PHP 過去會自動把型別當成可為 null。PHP 8.4 起這種隱含寫法變成 Deprecated,而且函式沒被呼叫也會出現。實測訊息與修法。

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 的結果。

關於作者

已發表 274 篇文章

留言

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

發表留言

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

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