5

这是来自 php 手册:http ://us.php.net/manual/en/language.constants.syntax.php

如果您使用未定义的常量,PHP 假定您指的是常量本身的名称,就像您将其称为字符串一样(CONSTANT 与“CONSTANT”)。发生这种情况时将发出 E_NOTICE 级别的错误。

我真的不喜欢这种行为。如果我未能定义所需的常量,我宁愿脚本失败,以便我被迫定义它。如果 PHP 尝试使用未定义的常量,有什么方法可以强制 PHP 使脚本崩溃?

例如。这两个脚本都做同样的事情。

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

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

我宁愿第二个脚本 DIE 并声明它试图使用未定义的常量 DEBUG。

4

3 回答 3

5

你可以做这样的事情(丑陋):

伪代码:

/**
 * 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");
于 2010-05-11T17:11:17.507 回答
1

我认为没有办法更改抛出的错误类型,但您可以将错误报告更改为E_ALL使用error_reporting以便在开发时看到这些错误:

error_reporting(E_ALL);
于 2010-05-11T17:10:43.170 回答
1
if(!defined('DEBUG')) die('failed.');
于 2010-05-11T16:56:21.613 回答