注意:未定义的变量
Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major 07001 with 07002 turned on. 07003 level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. 07004 language construct can be used to detect if a variable has been already initialized. Additionally and more ideal is the solution of 07005 since it does not generate a warning or error message if the variable is not initialized.
From PHP documentation,
No warning is generated if the variable does not exist. That means
empty() is essentially the concise equivalent to !isset($var) || $var
== false.
This means that you could use only empty() to determine if the variable is set, and in addition it checks the variable against the following, 0,"",null.
$o = [];
$var = ["",0,null,1,2,3,$foo,$o['myIndex']];
array_walk($var,function($v){
if(!isset($v) || $v == false) {
echo "empty\n";
}
if(empty($v)) {
echo "empty\n";
}
});
虽然PHP不需要变量声明,但它建议它,以避免一些安全漏洞或错误,其中人们会忘记给一个变量,他将在脚本中稍后使用的值。什么PHP在未声明的变量的情况下发出一个非常低级别的错误,E_NOTICE,一个甚至不报告默认情况下,但手动advises to allow在开发过程中。
处理问题的方法:
>推荐:声明变量,例如当您尝试将字符串附加到未定义的变量时。或者使用isset()/!empty()检查是否在引用它们之前声明它们,如:
//Initializing variable
$value = ""; //Initialization value; Examples
//"" When you want to append stuff later
//0 When you want to add numbers later
//isset()
$value = isset($_POST['value']) ? $_POST['value'] : '';
//empty()
$value = !empty($_POST['value']) ? $_POST['value'] : '';
>为E_NOTICE设置一个custom error handler,并将消息从标准输出(也许到日志文件)中重定向:
set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT)
>从报告中禁用E_NOTICE。只排除E_NOTICE的快速方法是:
error_reporting( error_reporting() & ~E_NOTICE )
注意:强烈建议只实现第1点。
注意:未定义索引/未定义偏移
当您(或PHP)尝试访问数组的未定义索引时,会出现此通知。
处理问题的方法:
>在访问索引之前检查索引是否存在。为此,您可以使用isset()或array_key_exists():
//isset()
$value = isset($array['my_index']) ? $array['my_index'] : '';
//array_key_exists()
$value = array_key_exists('my_index', $array) ? $array['my_index'] : '';
>当它尝试访问不存在的数组索引时,语言构造list()可能生成这个:
list($a, $b) = array(0 => 'a');
//or
list($one, $two) = explode(',', 'test string');
两个变量用于访问两个数组元素,但是只有一个数组元素,索引为0,因此将生成:
Notice: Undefined offset: 1
_ _POST / $ _GET / $ _SESSION变量
当使用$ _POST,$ _GET或$ _SESSION时,上面的注意事项经常出现。对于$ _POST和$ _GET,你只需要检查索引是否存在,在使用它们之前。对于$ _SESSION,您必须确保您的会话以session_start()开始,并且索引也存在。
还要注意,所有3个变量都是superglobals.这意味着它们需要以大写写。
有关: