Reputation: 227
In my code I use a php variable to display errors, such as
<span class="error"><?php echo $emailError; ?></span>
I only define the variable when there is an error to fill it with, so now XAMPP displays this error
Notice: Undefined variable: emailError
Its only a notice, so when deploying the code I would disable notices, or I could define everything before to make it go away.
$emailError = "";
$usernameError = "";
$firstnameError = "";
$lastnameError = "";
$languageError = "";
$passwordError = "";
$username = "";
$firstname = "";
$lastname = "";
$email = "";
But I find it weird to see something like this in my code, so my question is. Is it bad practice to only assign variables when needed, but always try to display them?
Upvotes: 0
Views: 990
Reputation: 141839
Yes, it is a bad practice. Initializing it to the empty string like you have shown is the best solution. Alternatively you could use the null coalescing operator like this:
<?php echo $emailError ?? ''; ?>
Although you need to do that every time you're not sure it's defined, so it's better just to initialize it like you have done.
As @Jeff pointed out, you might not want to have the span at all if there was no error in which case you should do something like this:
<?php if ( ! empty($emailError) ) { ?>
<span class="error"><?php echo $emailError; ?></span>
<?php } ?>
Upvotes: 5
Reputation: 1261
It is considered bad practice because it increases the chances of errors. I, however, use undeclared variables all the time, since it makes the code shorter, and if you are used to it, there is no problem.
Of course, your php settings need to be set to warn you (not) about undeclared variables. You can use error_reporting(...) to do that in php itself (on the go).
In the end it is just up to you. If you are a beginner, I encourage you to initialise all your variables and enjoy the blessings of the E_STRICT warnings to debug your code much more easily. Because you will not be the first one to be looking for three hours why $place = $p1ace / 2
; doesn't work.
Upvotes: 1