“Notice: Undefined variable”, “Notice: Undefined index”, and “Notice: Undefined offset” using PHP

后端 未结 28 906
盖世英雄少女心
盖世英雄少女心 2021-01-24 14:18

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

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

28条回答
  •  生来不讨喜
    2021-01-24 14:55

    These errors occur whenever we are using a variable that is not set.

    The best way to deal with these is set error reporting on while development.

    To set error reporting on:

    ini_set('error_reporting', 'on');
    ini_set('display_errors', 'on');
    error_reporting(E_ALL);
    

    On production servers, error reporting is off, therefore, we do not get these errors.

    On the development server, however, we can set error reporting on.

    To get rid of this error, we see the following example:

    if ($my == 9) {
     $test = 'yes';  // Will produce error as $my is not 9.
    }
    echo $test;
    

    We can initialize the variables to NULL before assigning their values or using them.

    So, we can modify the code as:

    $test = NULL;
    if ($my == 9) {
     $test = 'yes';  // Will produce error as $my is not 9.
    }
    echo $test;
    

    This will not disturb any program logic and will not produce Notice even if $test does not have value.

    So, basically, its always better to set error reporting ON for development.

    And fix all the errors.

    And on production, error reporting should be set to off.

提交回复
热议问题