gpt4 book ai didi

php - 为什么我应该修复 E_NOTICE 错误?

转载 作者:IT王子 更新时间:2023-10-29 01:10:22 25 4
gpt4 key购买 nike

作为一名开发人员,我在打开 E_NOTICE 的情况下工作。不过最近有人问我为什么要修复 E_NOTICE 错误。我能想到的唯一原因是纠正这些问题是最佳实践。

还有其他人有任何理由证明花费额外的时间/成本来纠正这些问题是合理的吗?

更具体地说,如果代码已经有效,为什么经理还要花钱来修复这些问题?

最佳答案

摘要

PHP Runtime Configuration Docs告诉你为什么:

Enabling E_NOTICE during development has some benefits.

For debugging purposes: NOTICE messages will warn you about possible bugs in your code. For example, use of unassigned values is warned. It is extremely useful to find typos and to save time for debugging.

NOTICE messages will warn you about bad style. For example, $arr[item] is better to be written as $arr['item'] since PHP tries to treat "item" as constant. If it is not a constant, PHP assumes it is a string index for the array.

这里有一个更详细的解释...


1.检测错别字

E_NOTICE 的主要原因错误是拼写错误。

示例 - notice.php

<?php
$username = 'joe'; // in real life this would be from $_SESSION

// and then much further down in the code...

if ($usernmae) { // typo, $usernmae expands to null
echo "Logged in";
}
else {
echo "Please log in...";
}
?>

不带 E_NOTICE 的输出

Please log in...

错了!你不是那个意思!

使用 E_NOTICE 输出

Notice: Undefined variable: usernmae in /home/user/notice.php on line 3
Please log in...

在 PHP 中,不存在的变量将返回 null 而不是导致错误,这可能导致代码的行为与预期不同,因此最好注意 E_NOTICE警告。


<强>2。检测不明确的数组索引

它还会警告您可能会更改的数组索引,例如

示例 - 今天的代码如下所示

<?php

$arr = array();
$arr['username'] = 'fred';

// then further down

echo $arr[username];
?>

不带 E_NOTICE 的输出

fred

示例 - 明天您将包含一个库

<?php
// tomorrow someone adds this
include_once('somelib.php');

$arr = array();
$arr['username'] = 'fred';

// then further down

echo $arr[username];
?>

图书馆会做这样的事情:

<?php
define("username", "Mary");
?>

新输出

空,因为现在它扩展为:

echo $arr["Mary"];

并且没有 key Mary$arr .

使用 E_NOTICE 输出

如果程序员有 E_NOTICE开启,PHP 会打印一条错误消息:

Notice: Use of undefined constant username - assumed 'username' in /home/user/example2.php on line 8
fred

3.最好的理由

如果您不修复所有 E_NOTICE您认为不是错误的错误,您可能会变得自满,并开始忽略消息,然后有一天当真正的错误发生时,您不会注意到它。

关于php - 为什么我应该修复 E_NOTICE 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5073642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com