The PHP book I read has a debugging script in it that is set to detect all erros and plaster them on the screen.
However, I keep getting pages of erros related to…
An error occurred in script ‘/Users/user1/Documents/DEV/+htdocs/SeminarRegistration/103_SignIn.php’ on line 17: Undefined index: email
What is the best way to prevent this “Notice”??
One thing I find annoying about PHP is an inability to define variable types?! Is there a way to at least initialize variables if you can’t “type” them??
You actually have to check to see if the key exists with isset($_POST[‘email’]) (isset() is special – it won’t throw the notice). It’s kind of lame and stupid, but that’s PHP for you. You can wrap it in a function/method to make it less annoying, or fill the respective array with missing keys.
There is no variable initialization (except fields in classes). You can only set a variable.
Note: Setting a variable to NULL in PHP does not delete that variable, unlike some dynamic languages.
Also, you can disable notices altogether, although that may make it harder to catch variable typos.
If you can install the class HTTP extension (from pecl, it’s called pecl_http), then you can use HttpQueryString class and can handle request vars in much better way:
This will return the value of POST or GET ‘email’ value or null if it’s not set. The nice thing is that you can define a default ‘fallback’ value in case the param is not set:
$email = $oRequest->get(‘email’, HttpQueryString::TYPE_STRING, ‘default@email.com’);
So you will never get the undefined index when using this class to access request variables.
I’ve seen someone handle undefined variables and indexes with a custom getIfSet() function. If I recall correctly, it took a variable (e.g. $test, $test[‘key’]), and an optional default value. Within the function it did a isset(), and if it was set, would return it’s value, otherwise returning the null or the optional default value.
I’m not saying that’s the best solution, but it’s A solution. Generally speaking though, global helper functions in an OO application are not recommended as objects become dependant on them, and as a result less portable. It’s important however not to forget the reason this notice exists. It exists to assist in debugging, by alerting you of undefined variables which may be causing unpredictable behaviour, so only use checks such as isset() and getIfSet() if it’s expected that the variable may not be defined. Using such checks anywhere else creates messy convoluted code, and defeats the point of having this notice.