[php]php 8 How to solve this error? strlen(): Passing null to parameter #1 ($string) of type string is deprecated in

參考網址:question2answer

Before PHP 8.1:

echo strlen(null); // No deprecation notice is shown up.
// -> 0

As of PHP 8.1:

echo strlen(null); // Deprecated: strlen(): Passing null to parameter #1 ($string) of type string is deprecated in ... on line ...
// -> 0

Solution

The RFC describing this issue is really helpful for possible resolutions and I highly recommend reviewing it. As of Question2Answer, the official resolution was to make use of the Null Coalescing Operator (??) when possible; here is an example from GitHub, which replaces:

if (strlen($error )) {...}

with this:

if (strlen($error ?? '')) {...}

This effectively fixes the issue.

 

合併運算子(??)
php7開始支援
PHP 7 新特性二Null coalescing operator(空合并运算符)
空值合併運算子

如要相容於php5.6得改掉「??」
 

https://github.com/tad0616/tadnews/commit/master
修正PHP5.x會出錯的問題
$result['of_ncsn'][$ncsn] = $page['of_ncsn'] ?? $the_ncsn;
$result['of_ncsn'][$ncsn] = isset($page['of_ncsn']) ? $page['of_ncsn'] : $the_ncsn;

 

本篇發表於 程式設計。將永久鏈結加入書籤。