Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a config option in PHP to prevent undefined constants from being interpreted as strings?

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.

like image 644
mrbinky3000 Avatar asked May 11 '10 16:05

mrbinky3000


1 Answers

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");
  • Check out set_error_handler()
  • Check also this great comment: http://us.php.net/manual/en/class.errorexception.php#95415
like image 131
powtac Avatar answered Nov 15 '22 04:11

powtac