Featured image of post [PHP] 升級 PHP 8.2 後出現警告訊息: Using ${expr} (variable variables) in strings is deprecated

[PHP] 升級 PHP 8.2 後出現警告訊息: Using ${expr} (variable variables) in strings is deprecated

PHP 升級到 8.2 版後開始大量出現 warning logs:

1
Warning: Using ${expr} (variable variables) in strings is deprecated, use {${expr}} instead in /home/calos/projects/laravel/app/Models/User.php on line 764

原因是 PHP RFC: Deprecate ${} string interpolation 已在 PHP 8.2 實施,所以會開始看到這類訊息。

這個 RFC 是關於字串內指定變數的使用方式,目前有四種使用方式:

  1. Directly embedding variables ("$foo")
  2. Braces outside the variable ("{$foo}")
  3. Braces after the dollar sign ("${foo}")
  4. Variable variables ("${expr}", equivalent to (string) ${expr})

RFC 提議刪除較容易混淆的第 3 種與第 4 種使用方式,目前在 PHP 8.2 開始會看到 warning logs,在 PHP 9.0 版正式移除,如果有使用到的話在 PHP 9.0 正式釋出並且升級之前需要做修正。

我個人早期學習 PHP 是使用第一種方法 ("$foo"),後期開始使用 VScode 作為主要的開發用 IDE 後,因為 VScode 預設會為第二種方法 ("{$foo}") 做 highlight。

至於為什麼我會遇到這個東西?其實我不知道可以使用第 3 種和第 4 種方法,看到這個資訊我也是一頭霧水,因為我不記得我有這樣用過,程式也沒有問題。

多看了幾遍程式碼之後終於發現問題所在

1
2
3
4
5
                                           here
                                             |
                                             v
- throw new Exception("Algorithm for column '${$column}' not defined.");
+ throw new Exception("Algorithm for column '{$column}' not defined.");

原來是我不小心多打一個錢號,笑死。


References: