[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開始支援

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