tomsseisums
tomsseisums

Reputation: 13357

Drawbacks when using undefined constants as variables

Huh, don't know what to search for, therefore have no idea if this is a duplicate or not.

Example:

function foo($bar){
    switch($bar)
        case UNDEFINED:
            return 'foo';
        break;
        case DEFINED:
            return 'bar';
        break;
        default:
            return 'no foo and no bar';
    }
}

echo foo(DEFINED); # edited: had $ before function call
// bar

echo foo(OUTPUT);
// no foo and no bar

PHP (version 5.3) doesn't throw any errors, but are there any drawbacks to this?

Upvotes: 1

Views: 66

Answers (1)

Michael Spector
Michael Spector

Reputation: 36999

Undefined constants are interpreted as strings. In your case these would be two strings "DEFINED" and "UNDEFINED". From the PHP manual:

If you use an undefined constant, PHP assumes that you mean the name of the constant itself, just as if you called it as a string (CONSTANT vs "CONSTANT"). An error of level E_NOTICE will be issued when this happens.

EDIT Ignoring E_NOTICE is considered to be bad style, this is from PHP documentation:

Enabling E_NOTICE during development has some benefits. For debugging purposes: NOTICE messages will warn you about possible bugs in your code. For example, use of unassigned values is warned. It is extremely useful to find typos and to save time for debugging. NOTICE messages will warn you about bad style. For example, $arr[item] is better to be written as $arr['item'] since PHP tries to treat "item" as constant. If it is not a constant, PHP assumes it is a string index for the array.

Upvotes: 3

Related Questions