PHP7.4兼容性错误:Trying to access array offset on value of type null

PHP与SEO 思享 1621浏览

自己写了一个post请求的函数,能够正常运行输出结果,但是会产生大量“Trying to access array offset on value of type null”错误的日志。网上找了找说是PHP7.4兼容性的问题

问题原因

参考:https://www.php.net/manual/en/migration74.incompatible.php

Trying to use values of type null, bool, int, float or resource as an array (such as $null["key"]) will now generate a notice.

百度翻译:尝试使用null、bool、int、float或resource类型的值作为数组(例如$null[“key”])将生成一个通知。

问题解决

说实话本小白也没看明白是啥意思,通过一步步删减代码测试,终于测试出出现错误的代码。

举例:

$result = $result['msg'];

根据错误原因,我的理解是如果数组"msg"不存在,就会触发这个错误,但我感觉好想存在也会,不知道是不是我的错觉,反正也懒得测试了,解决办法就是在使用前加一层判断

示例:

if(!empty($result['msg'])) {
    $result = $result['msg'];
}

这样就不报错了,不过还是感觉有点怪怪的,很粗糙。如果有大佬欢迎指教

推荐阅读

Function get_magic_quotes_gpc() is deprecated报错解决办法

在 PHP 7.4 及更高版本中, get_magic_quotes_gpc() 函数已被弃用。 This means that code using this function will raise a warning or error.以下是解决......

PHP提示:Warning: count():Parameter must be an array or an object that implements Countable

错误原因:PHP7.2以后,count()函数的参数无效时会抛出warning警告。...

PHP7.4 报错:Deprecated Functionality: implode(): Passing glue string after array is deprecated.

PHP7.4运行项目报错:Deprecated Functionality: implode(): Passing glue string after array is deprecated。只需交换 implode() 函数的两个参数!...