php 消息:尝试访问类型为 null 的值的数组偏移量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/59336951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Message: Trying to access array offset on value of type null
提问by vespino
I'm getting this error on multiple occasion in a script (invoiceplane) I have been using for a few years now but which hasn't been maintained unfortunately by its creators:
我在脚本(发票平面)中多次遇到此错误,我已经使用了几年,但不幸的是它的创建者没有维护它:
Message: Trying to access array offset on value of type null
My server has been upgrade to PHP 7.4 and I'm looking for a way to fix the issues and maintain the script myself since I'm very happy with it.
我的服务器已升级到 PHP 7.4,我正在寻找一种方法来解决问题并自己维护脚本,因为我对它非常满意。
This is what's on the line that gives the error:
这是给出错误的行上的内容:
$len = $cOTLdata['char_data'] === null ? 0 : count($cOTLdata['char_data']);
$cOTLdata is passed to the function:
$cOTLdata 传递给函数:
public function trimOTLdata(&$cOTLdata, $Left = true, $Right = true)
{
$len = $cOTLdata['char_data'] === null ? 0 : count($cOTLdata['char_data']);
$nLeft = 0;
$nRight = 0;
//etc
It's included in mpdfbtw, but simply overwriting the files from the github repository did not fix the errors.
顺便说一句,它包含在mpdf 中,但简单地覆盖 github 存储库中的文件并不能修复错误。
回答by ArSeN
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.
发生这种情况是因为$cOTLdata
它不为空但索引'char_data'
不存在。以前版本的 PHP 可能对此类错误不那么严格,并且默默地吞下了错误/通知,而 7.4 不再这样做了。
To check whether the index exists or not you can use isset():
要检查索引是否存在,您可以使用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).
注意我切换了三元运算符的 then 和 else 情况,因为 === null 本质上是 isset 已经做的(但在积极的情况下)。