dongmaonao0505 2010-05-11 16:53
浏览 84
已采纳

在PHP中是否有一个配置选项来防止未定义的常量被解释为字符串?

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.

  • 写回答

3条回答 默认 最新

  • dsio68964998 2010-05-11 17:11
    关注

    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");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)