views:

75

answers:

3

This is from the php manual: http://us.php.net/manual/en/language.constants.syntax.php

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.

I really don't like this behavior. If I have failed to define a required constant, I would rather the script fail so that I am forced define it. Is there any way to force PHP to crash the script if it tries to use an undefined constant?

For example. Both of these scripts do the same thing.

<?php
define('DEBUG',1);
if (DEBUG) echo('Yo!');
?>

and

<?php
if(DEBUG) echo('Yo!');
?>

I would rather the second script DIE and declare that it tried to use an undefined constant DEBUG.

+1  A: 
if(!defined('DEBUG')) die('failed.');
scaryzet
I think he wants the warning to raise an E_ERROR...
Byron Whitlock
@scaryzet I know I could do that, but I was hoping for a more elegant solution.@Byron Yes, I would like for PHP to declare and E_ERROR instead of an E_NOTICE
mrbinky3000
+1  A: 

I don't think there's a way to change the type of error thrown, but you can change the error reporting to E_ALL using error_reporting so that you see these errors while developing:

error_reporting(E_ALL);
Geoff
But with this a Notice remains a Notice!
powtac
+2  A: 

You could do something (ugly) like this:

pseudo code:

/**
 * A Notice becomes an Error :)
 */
function myErrorHandler($errno, $errstr, $errfile, $errline) {
    if ($errno == E_NOTICE) { // = 8 
        if (substr($errstr ... )) { // contains something which looks like a constant notice...   
             trigger_error('A constant was not defined!', E_USER_ERROR);
        }
    }
}
set_error_handler("myErrorHandler");
powtac
The error code for using an undefined constant appears to be 8.
Tgr
Thanks Tgr! I changed the PHP constant to E_USER_NOTICE.
powtac
+1 - Better answer than mine. Probably a good idea to only set this error handle when debugging since it hinges on a substring check which may be slow (and may give some false positives).
Geoff
Thanks everyone. The pseudo code is a good start for me to work with. @future readers: remember, the above is "pseudo". Make it work for yourself.
mrbinky3000