可以这样修复通知:php 中未定义的索引错误吗?



我的任务是完成我学校的三个前学生一直在做的一个项目,并且无法联系到前两个正在工作的项目,而且由于它现在已经启动并运行,我无法根据现实以外的任何其他方式测试系统,有时可能不是最好的测试服务器。现在我在前两个编写的错误报告脚本中有一个错误,它是一个 注意:第 73-75 行上的未定义索引,这些行如下所示:

$text .= $t['file'] . "n";
$text .= $t['line'] . "n";
$text .= print_r($t['file'], 1) . "n";

第 72 行如下所示:

$text .= ((isset($t['type']) && isset($t['object'])) ? print_r($t['object'], true) . $t['type'] . $t['function'] : $t['function']) . "n";

所以我想知道的是,如果在第 72 行添加这样的 if 语句,问题是否会得到解决:

$text .= if((isset($t['type']) && isset($t['object'])) ? print_r($t['object'], true) . $t['type'] . $t['function'] : $t['function']) . "n";

更好的检查将是下一个:

if( isset( $t['file'] ) ) {
    $text .= $t['file'] . "n";
}
if( isset( $t['line'] ) ) {
    $text .= $t['line'] . "n";
}
if( isset( $t['file'] ) ) {
    $text .= print_r($t['file'], 1) . "n";
}

此代码更易于阅读。

但我建议检测索引未定义的原因。这可能是导致 ща 其他更严重的逻辑错误.

切勿以这种方式抑制通知和警告,如果这些通知和警告是在长时间的良好工作之后出现的。首先,您必须检测它们出现的原因。

已经有一个三元运算符:

$var = (a == b) ? 'yes' : 'no';

如果 a == b,则 $var = '是' 否则$var = '否'

然后

((isset($t['type']) && isset($t['object'])) ? print_r($t['object'], true) . $t['type'] . $t['function'] : $t['function']) . "n";

if (isset($t['type']) && isset($t['object'])) {
    $text .= print_r($t['object'], true) . $t['type'] . $t['function'];
} else {
    $text .= $t['function'];
}

最新更新