“通知:未定义的变量",“通知:未定义的索引"和“通知:未定义的偏移量"使用PHP [英] "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

查看:135
本文介绍了“通知:未定义的变量",“通知:未定义的索引"和“通知:未定义的偏移量"使用PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行PHP脚本,并继续收到如下错误:

I'm running a PHP script and continue to receive errors like:

注意:未定义的变量:第10行的C:\ wamp \ www \ mypath \ index.php中的my_variable_name

Notice: Undefined variable: my_variable_name in C:\wamp\www\mypath\index.php on line 10

注意:未定义的索引:第11行的my_index C:\ wamp \ www \ mypath \ index.php

Notice: Undefined index: my_index C:\wamp\www\mypath\index.php on line 11

第10行和第11行看起来像这样:

Line 10 and 11 looks like this:

echo "My variable value is: " . $my_variable_name;
echo "My index value is: " . $my_array["my_index"];

这些错误消息是什么意思?

What is the meaning of these error messages?

为什么它们突然出现?我曾经使用此脚本多年,但从未遇到任何问题.

Why do they appear all of a sudden? I used to use this script for years and I've never had any problem.

我该如何解决?

这是一个通用参考问题,人们可以重复链接到该链接,而不必一遍又一遍地说明问题.我认为这是必要的,因为在此问题上,大多数现实世界的答案都是非常具体的.

This is a General Reference question for people to link to as duplicate, instead of having to explain the issue over and over again. I feel this is necessary because most real-world answers on this issue are very specific.

相关元讨论:

  • What can be done about repetitive questions?
  • Do "reference questions" make sense?

推荐答案

注意:未定义的变量

根据 PHP手册的广泛见解:

在将一个文件包含在另一个使用相同变量名的文件中的情况下,依靠未初始化变量的默认值是有问题的.这也是 E_NOTICE 级错误在使用未初始化的变量的情况下,但是在将元素附加到未初始化的数组的情况下则不是. isset()语言结构可用于检测变量是否已被已经初始化.另外,更理想的是 empty()的解决方案,因为它不会生成警告或错误消息(如果未初始化变量).

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 security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized. Additionally and more ideal is the solution of empty() since it does not generate a warning or error message if the variable is not initialized.

来自 PHP文档:

如果变量不存在,则不会生成任何警告.那意味着 empty()本质上等同于!isset($ var)||的简洁含义. $ var ==假.

No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.

这意味着您只能使用empty()来确定是否设置了变量,此外,它还会根据以下变量检查变量:00.0"""0"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, 0.0, "", "0", null, false or [].

示例:

$o = [];
@$var = ["",0,null,1,2,3,$foo,$o['myIndex']];
array_walk($var, function($v) {
    echo (!isset($v) || $v == false) ? 'true ' : 'false';
    echo ' ' . (empty($v) ? 'true' : 'false');
    echo "\n";
});

3v4l.org在线PHP编辑器中测试以上代码段

尽管PHP不需要变量声明,但它确实推荐这样做,以避免某些安全性漏洞或bug,因为这些漏洞或bug可能会忘记为变量提供值,该变量将在脚本的后面使用.在未声明变量的情况下,PHP会发出一个非常低级的错误E_NOTICE,默认情况下甚至不会报告该错误,但是手册

Although PHP does not require a variable declaration, it does recommend it in order to avoid some security vulnerabilities or bugs where one would forget to give a value to a variable that will be used later in the script. What PHP does in the case of undeclared variables is issue a very low level error, E_NOTICE, one that is not even reported by default, but the Manual advises to allow during development.

解决问题的方法:

  1. 推荐:声明变量,例如,当您尝试将字符串附加到未定义的变量时.或使用 isset() /

  1. Recommended: Declare your variables, for example when you try to append a string to an undefined variable. Or use isset() / !empty() to check if they are declared before referencing them, as in:

//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'] : '';

从PHP 7.0开始,它变得更加干净,现在您可以使用空合并运算符 :

This has become much cleaner as of PHP 7.0, now you can use the null coalesce operator:

// Null coalesce operator - No need to explicitly initialize the variable.
$value = $_POST['value'] ?? '';

  • 设置自定义错误处理程序为E_NOTICE并将消息重定向到标准输出之外(也许到日志文件):

  • Set a custom error handler for E_NOTICE and redirect the messages away from the standard output (maybe to a log file):

    set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT)
    

  • 禁用E_NOTICE的报告功能.仅排除E_NOTICE的一种快速方法是:

  • Disable E_NOTICE from reporting. A quick way to exclude just E_NOTICE is:

    error_reporting( error_reporting() & ~E_NOTICE )
    

  • 使用 @运算符抑制该错误.

  • Suppress the error with the @ operator.

    注意:强烈建议仅实施第1点.

    Note: It's strongly recommended to implement just point 1.

    当您(或PHP)尝试访问数组的未定义索引时,将显示此通知.

    This notice appears when you (or PHP) try to access an undefined index of an array.

    解决问题的方法:

    1. 在访问索引之前检查索引是否存在.为此,您可以使用 isset()

    2. 语言构造 list() 可能会在生成时尝试访问不存在的数组索引:

    3. The language construct list() may generate this when it attempts to access an array index that does not exist:

      list($a, $b) = array(0 => 'a');
      //or
      list($one, $two) = explode(',', 'test string');
      

    4. 两个变量用于访问两个数组元素,但是只有一个数组元素,索引为0,因此将生成:

      Two variables are used to access two array elements, however there is only one array element, index 0, so this will generate:

      注意:未定义的偏移量:1

      Notice: Undefined offset: 1

      $_POST/$_GET/$_SESSION变量

      使用$_POST$_GET$_SESSION时,经常会出现上述提示.对于$_POST$_GET,您只需要在使用索引之前检查索引是否存在.对于$_SESSION,您必须确保以 session_start() 并且该索引也存在.

      $_POST / $_GET / $_SESSION variable

      The notices above appear often when working with $_POST, $_GET or $_SESSION. For $_POST and $_GET you just have to check if the index exists or not before you use them. For $_SESSION you have to make sure you have the session started with session_start() and that the index also exists.

      还要注意,所有3个变量都是 superglobals 且均为大写.

      Also note that all 3 variables are superglobals and are uppercase.

      相关:

      • Notice: Undefined variable
      • Notice: Undefined Index

      这篇关于“通知:未定义的变量",“通知:未定义的索引"和“通知:未定义的偏移量"使用PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆