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

后端 未结 28 914
盖世英雄少女心
盖世英雄少女心 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 15:03

    If working with classes you need to make sure you reference member variables using $this:

    class Person
    {
        protected $firstName;
        protected $lastName;
    
        public function setFullName($first, $last)
        {
            // Correct
            $this->firstName = $first;
    
            // Incorrect
            $lastName = $last;
    
            // Incorrect
            $this->$lastName = $last;
        }
    }
    
    0 讨论(0)
  • 2021-01-24 15:03

    Another reason why an undefined index notice will be thrown, would be that a column was omitted from a database query.

    I.e.:

    $query = "SELECT col1 FROM table WHERE col_x = ?";
    

    Then trying to access more columns/rows inside a loop.

    I.e.:

    print_r($row['col1']);
    print_r($row['col2']); // undefined index thrown
    

    or in a while loop:

    while( $row = fetching_function($query) ) {
    
        echo $row['col1'];
        echo "<br>";
        echo $row['col2']; // undefined index thrown
        echo "<br>";
        echo $row['col3']; // undefined index thrown
    
    }
    

    Something else that needs to be noted is that on a *NIX OS and Mac OS X, things are case-sensitive.

    Consult the followning Q&A's on Stack:

    • Are table names in MySQL case sensitive?

    • mysql case sensitive table names in queries

    • MySql - Case Sensitive issue of tables in different server

    0 讨论(0)
  • 2021-01-24 15:04

    WHY IS THIS HAPPENING?

    Over time, PHP has become a more security-focused language. Settings which used to be turned off by default are now turned on by default. A perfect example of this is E_STRICT, which became turned on by default as of PHP 5.4.0.

    Furthermore, according to PHP documentation, by default, E_NOTICE is disabled in php.ini. PHP docs recommend turning it on for debugging purposes. However, when I download PHP from the Ubuntu repository–and from BitNami's Windows stack–I see something else.

    ; Common Values:
    ;   E_ALL (Show all errors, warnings and notices including coding standards.)
    ;   E_ALL & ~E_NOTICE  (Show all errors, except for notices)
    ;   E_ALL & ~E_NOTICE & ~E_STRICT  (Show all errors, except for notices and coding standards warnings.)
    ;   E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR  (Show only errors)
    ; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
    ; Development Value: E_ALL
    ; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT
    ; http://php.net/error-reporting
    error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
    

    Notice that error_reporting is actually set to the production value by default, not to the "default" value by default. This is somewhat confusing and is not documented outside of php.ini, so I have not validated this on other distributions.

    To answer your question, however, this error pops up now when it did not pop up before because:

    1. You installed PHP and the new default settings are somewhat poorly documented but do not exclude E_NOTICE.

    2. E_NOTICE warnings like undefined variables and undefined indexes actually help to make your code cleaner and safer. I can tell you that, years ago, keeping E_NOTICE enabled forced me to declare my variables. It made it a LOT easier to learn C, were not declaring variables is much bigger of a nuisance.

    WHAT CAN I DO ABOUT IT?

    1. Turn off E_NOTICE by copying the "Default value" E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED and replacing it with what is currently uncommented after the equals sign in error_reporting =. Restart Apache, or PHP if using CGI or FPM. Make sure you are editing the "right" php.ini. The correct one will be Apache if you are running PHP with Apache, fpm or php-fpm if running PHP-FPM, cgi if running PHP-CGI, etc. This is not the recommended method, but if you have legacy code that's going to be exceedingly difficult to edit, then it might be your best bet.

    2. Turn off E_NOTICE on the file or folder level. This might be preferable if you have some legacy code but want to do things the "right" way otherwise. To do this, you should consult Apache2, Nginx, or whatever your server of choice is. In Apache, you would use php_value inside of <Directory>.

    3. Rewrite your code to be cleaner. If you need to do this while moving to a production environment or don't want someone to see your errors, make sure you are disabling any display of errors, and only logging your errors (see display_errors and log_errors in php.ini and your server settings).

    To expand on option 3: This is the ideal. If you can go this route, you should. If you are not going this route initially, consider moving this route eventually by testing your code in a development environment. While you're at it, get rid of ~E_STRICT and ~E_DEPRECATED to see what might go wrong in the future. You're going to see a LOT of unfamiliar errors, but it's going to stop you from having any unpleasant problems when you need to upgrade PHP in the future.

    WHAT DO THE ERRORS MEAN?

    Undefined variable: my_variable_name - This occurs when a variable has not been defined before use. When the PHP script is executed, it internally just assumes a null value. However, in which scenario would you need to check a variable before it was defined? Ultimately, this is an argument for "sloppy code". As a developer, I can tell you that I love it when I see an open source project where variables are defined as high up in their scopes as they can be defined. It makes it easier to tell what variables are going to pop up in the future and makes it easier to read/learn the code.

    function foo()
    {
        $my_variable_name = '';
    
        //....
    
        if ($my_variable_name) {
            // perform some logic
        }
    }
    

    Undefined index: my_index - This occurs when you try to access a value in an array and it does not exist. To prevent this error, perform a conditional check.

    // verbose way - generally better
    if (isset($my_array['my_index'])) {
        echo "My index value is: " . $my_array['my_index'];
    }
    
    // non-verbose ternary example - I use this sometimes for small rules.
    $my_index_val = isset($my_array['my_index'])?$my_array['my_index']:'(undefined)';
    echo "My index value is: " . $my_index_val;   
    

    Another option is to declare an empty array at the top of your function. This is not always possible.

    $my_array = array(
        'my_index' => ''
    );
    
    //...
    
    $my_array['my_index'] = 'new string';
    

    (additional tip)

    • When I was encountering these and other issues, I used NetBeans IDE (free) and it gave me a host of warnings and notices. Some of them offer very helpful tips. This is not a requirement, and I don't use IDEs anymore except for large projects. I'm more of a vim person these days :).
    0 讨论(0)
  • 2021-01-24 15:04

    why not keep things simple?

    <?php
    error_reporting(E_ALL); // making sure all notices are on
    
    function idxVal(&$var, $default = null) {
             return empty($var) ? $var = $default : $var;
      }
    
    echo idxVal($arr['test']);         // returns null without any notice
    echo idxVal($arr['hey ho'], 'yo'); // returns yo and assigns it to array index, nice
    
    ?>
    
    0 讨论(0)
提交回复
热议问题