Click to See Complete Forum and Search --> : Using unset variables


kvirri
07-14-2007, 05:16 AM
I've been working a while on a script with some friends, and someone suggested that we'd all enable messages on all errors (notices, and so on). The example that was given was "you have to run first isset() on a variable before using it, if it might not be set. That's pro, and that's how everyone does it, anyway".

I don't get one thing, what's the advantage of using such a thing? I can disable notices (since they aren't errors in themselves and scripts work, too) and just check them against whatever i need. If they are not set, they will return 0 anyway, and I will save a few cpu cycles by not running a command.

What's the whole fuss with coding in this style, and genneraly, checking a script to be notice-free?

I'm not asking this so to cause a flame (if it's a controversial subject) but I merley want to understand this stuff.
Thanks!

NogDog
07-14-2007, 12:09 PM
In some programming languages, you cannot use a variable until it has been "declared". This was often due to the need to allocate memory for the variable, but it also has the benefit of helping the programmer avoid variable name spelling mistakes.

PHP is much "looser" in this respect. It will even allow you check the value of a variable that has never been set in your script (only throwing a notice-level warning if you do so). But this looseness can lead to problems. Fore example, if you misspell a variable name:

if(rand(0,1)) // set $variable to true or false:
{
$variable = TRUE;
}
else
{
$variable = FALSE;
}

// ...later...

if($variabel) // misspelled variable name
{
echo "got here"; // will never execute since $variabel will always
// evaluate as FALSE, due to not being set yet
}

So, if while using E_NOTICE (plus E_STRICT if PHP5) you can write your script so that no such notices/warnings are thrown, then you can have a higher degree of confidence that you have no spelling mistakes or other such errors that could cause bugs, such bugs often being of the type that can be very difficult to locate.