March 16, 2012

Fixing vs Hiding "Undefined Variable" Errors in PHP

Question by Chords

Depending on which error reporting I set, my web app either works or displays a ton of errors. I was under the impression I didn’t need to initiate variables in PHP but setting the second error reporting seems to require it. What is going here? Should I go through and initiate all my variables?

error_reporting(E_ALL ^ E_NOTICE);

error_reporting(E_ALL | E_STRICT);

Answer by todofixthis

You are asking about whether to suppress the warning for uninitialized variables, but the code you are posting suppresses ALL E_NOTICE warnings. This is not quite the same thing, but it’s as close as you can get directly to what you’re asking; there is no way to suppress only uninitialized variable notices.

In a way, notices are possibly the most important warning/error messages of all because they point out potential logic errors, which are among the most difficult to identify and fix.

Given your options:

  1. Suppress ALL E_NOTICE warnings.
  2. Fix all uninitialized variables in your code.

I would recommend going with #2. It’s more work upfront, but a well-timed E_NOTICE might just save you a whole mess of trouble one day.

Answer by Starx

You will receive a notice error, if you reference an identifier before they were initialised.

For example:

echo $variable; // is referencing to $variable which is not set before
echo $arrayname['indexname'] // it is also referencing to indexname item of array,
// if not found it will index another notice error

So, make sure you declare an identifier/variable before you reference it on our code, and you will be safe.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!