消息: 尝试访问 null 类型值上的数组偏移量

我在一个已经使用了几年的脚本(发票飞机)中多次遇到这个错误,但不幸的是创建者没有维护它:

Message: Trying to access array offset on value of type null

我的服务器已经升级到 PHP 7.4,我正在寻找一种方法来解决这个问题,并维护自己的脚本,因为我很高兴。

这就是产生错误的原因:

$len = $cOTLdata['char_data'] === null ? 0 : count($cOTLdata['char_data']);

$cOTLdata 被传递给函数:

public function trimOTLdata(&$cOTLdata, $Left = true, $Right = true)
{
$len = $cOTLdata['char_data'] === null ? 0 : count($cOTLdata['char_data']);
$nLeft = 0;
$nRight = 0;
//etc

顺便说一下,它包含在 MPDF中,但是仅仅覆盖 github 存储库中的文件并不能修复错误。

505484 次浏览

This happens because $cOTLdata is not null but the index 'char_data' does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.

To check whether the index exists or not you can use isset():

isset($cOTLdata['char_data'])

Which means the line should look something like this:

$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;

Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).