SUMMARY
The PHP 运行时配置文档让你知道为什么:
在开发过程中启用 E_NOTICE 有一些好处。
出于调试目的:NOTICE 消息将警告您代码中可能存在的错误。例如,使用未分配的值会受到警告。它对于查找拼写错误并节省调试时间非常有用。
NOTICE 消息会警告您不良风格。例如,$arr[item] 最好写为 $arr['item'],因为 PHP 尝试将“item”视为常量。如果它不是常量,PHP 会假定它是数组的字符串索引。
这是每个的更详细的解释...
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"];
并且没有钥匙Mary
in $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
当你认为不是错误的错误时,你可能会变得自满,并开始忽略这些消息,然后有一天,当真正的错误发生时,你不会注意到它。