Pregunta

I'm learning that I've gotten into a bad programming habit of not always defining variables or properties before using them in a comparison operator. I'd never noticed this before, but now that I'm developing in a different environment I'm getting the notices.

For example:

if ($test_var)
    echo "Do some stuff";

This is easy enough to solve with isset or empty depending on the need.

However, I also tend to use these undeclared variables/properties in comparisons like so:

if (($test_int == 1) && ($test_str == "hello world"))
    echo "Do some stuff";

This is a lot harder to rewrite with isset or empty statements. I could wrap the whole thing in a bunch of issets, but then you very quickly get nested spaghetti code that impacts readability and maintainability.

I understand WHY this is happening, but am looking for help finding the best solution as a general practice.

Apologies if this solution has been posted before. I looked, but all I could find were questions about why notices were appearing, not specifically how to write comparisons.

¿Fue útil?

Solución

I think the best way to go would be to initialise these variables you do comparisons on, by assigning some sort of value like null before your procedure.

$chicken = null;

// some code that generates $egg value

if ($egg) {
    $chicken = "Leghorn";
}


if ("Leghorn" === $chicken) {
    echo "I say ..I say...boy...";
}

So if $chicken = null; was missing in the example above, and the value of $egg was false, you would normally get a PHP notice.

Otros consejos

If you just want to get rid of the notices, check your error reporting settings: http://php.net/manual/en/function.error-reporting.php

(If you have a script that runs at the top of every page, you can do something like: error_reporting(E_ALL & ~E_NOTICE);

Otherwise, you could declare your variables near the top (probably a better idea).

Unrelated: It's a personal thing, but if you enclose your IF statements in braces, it'll be easier to decipher later!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top