How can i solve this php errorr“Notice: Undefined variable”?
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_globalsturned 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.
Some explanations:
Although PHP does not require 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 he will use 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.
Ways to deal with the issue:
- Recommended: Declare your variables. Or use isset to check if they are declared before referencing them.
- 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)
. - 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.
Note: It’s strongly recommended to implement just point 1.