开发者

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开发者_JS百科, 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.


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


if(!defined('DEBUG')) die('failed.');


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜