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

查看:54
本文介绍了“注意:未定义变量"、“注意:未定义索引"和“注意:未定义偏移"使用 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.

相关元讨论:

推荐答案

注意:未定义变量

来自PHP 手册:

在将一个文件包含到另一个使用相同变量名的文件中的情况下,依赖未初始化变量的默认值是有问题的.这也是一个主要的安全风险register_globals 已打开.发出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() 来确定变量是否已设置,此外它还会根据以下内容检查变量,0, 0.0"""0"nullfalse[].

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 不需要变量声明,但它确实推荐它以避免一些安全漏洞或错误,因为人们会忘记为稍后将在脚本中使用的变量赋值.PHP 在未声明变量的情况下所做的是发出一个非常低级别的错误,E_NOTICE,默认情况下甚至没有报告,但是 Manual 建议在开发过程中允许.

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()/!empty() 以在引用之前检查它们是否已声明他们,如:

  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 开始,这变得更加清晰,现在您可以使用 null 合并运算符:

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 的快速方法是:

    error_reporting( error_reporting() & ~E_NOTICE )
    

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

    注意:强烈建议只实施第 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()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() 可能会在尝试访问不存在的数组索引时生成:

  • 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');
    

  • 两个变量用来访问两个数组元素,但是数组元素只有一个,索引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.

    相关:

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

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