Hi! I'm Nathan Hoad


PHP: Undefined constants

What will the following code (in isolation) output?

if (SOME_DEFINE) {
    print 'yes';
} else {
    print 'no';
}

If you said no then you are sadly mistaken. PHP treats any undefined global constant as a string so the above code would read like this:

if ('SOME_DEFINE') {
    print 'yes';
} else {
    print 'no';
}

When it is written like that, it is a lot easier to see why yes is printed. Any string other than '' (empty string) evaluates to true.

This is one argument against using defines. Most would suggest using class constants instead.

If I just made your day a little better then thank me with a coffee or maybe a a pizza