Why should I fix E_NOTICE errors?

前端 未结 5 902
轻奢々
轻奢々 2020-11-27 20:30

As a developer, I work with E_NOTICE turned on. Recently though, I was asked why E_NOTICE errors should be fixed. The only reason that I could come up with was that it is be

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 21:09

    SUMMARY

    The PHP Runtime Configuration Docs give you some idea why:

    Enabling E_NOTICE during development has some benefits.

    For debugging purposes: NOTICE messages will warn you about possible bugs in your code. For example, use of unassigned values is warned. It is extremely useful to find typos and to save time for debugging.

    NOTICE messages will warn you about bad style. For example, $arr[item] is better to be written as $arr['item'] since PHP tries to treat "item" as constant. If it is not a constant, PHP assumes it is a string index for the array.

    Here's a more detailed explanation of each...


    1. TO DETECT TYPOS

    The main cause of E_NOTICE errors is typos.

    Example - notice.php

    
    

    Output without E_NOTICE

    Please log in...
    

    Wrong! You didn't mean that!

    Output with E_NOTICE

    Notice: Undefined variable: usernmae in /home/user/notice.php on line 3
    Please log in...
    

    In PHP, a variable that doesn't exist will return null rather than causing an error, and that could cause code to behave differently than expected, so it's best to heed E_NOTICE warnings.


    2. TO DETECT AMBIGUOUS ARRAY INDEXES

    It also warns you about array indexes that might change on you, e.g.

    Example - code looks like this today

    
    

    Output without E_NOTICE

    fred
    

    Example - tomorrow you include a library

    
    

    and the library does something like this:

    
    

    New output

    Empty, because now it expands to:

    echo $arr["Mary"];
    

    and there is no key Mary in $arr.

    Output with E_NOTICE

    If only the programmer had E_NOTICE on, PHP would have printed an error message:

    Notice: Use of undefined constant username - assumed 'username' in /home/user/example2.php on line 8
    fred
    

    3. THE BEST REASON

    If you don't fix all the E_NOTICE errors that you think aren't errors, you will probably grow complacent, and start ignoring the messages, and then one day when a real error happens, you won't notice it.

提交回复
热议问题