duanmei9980 2011-06-01 20:06
浏览 77
已采纳

为什么未定义的常量值为true?

Stupid question - I'm surprised this one has bitten me. Why do undefined constants in PHP evaluate to true?

Test case:

<?php
    if(WHATEVER_THIS_ISNT_DEFINED)
        echo 'Huh?';
?>

The above example prints 'Huh?'

Thanks so much for your help! :)

  • 写回答

7条回答 默认 最新

  • dongshang1529 2011-06-01 20:09
    关注

    Try defined('WHATEVER_THIS_ISNT_DEFINED')

    When PHP encounters a constant that is not defined, it throws an E_NOTICE, and uses the constant name you've tried to use as a string. That's why your snippet prints Huh!, because a non-empty string (which is not "0") will evaluate to true.

    From the manual:

    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.

    If you set your error reporting level to report E_NOTICEs, which is a good practice during development, you will also see the notice thrown.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接
  • ¥15 MATLAB中使用parfor,矩阵Removal的有效索引在parfor循环中受限制
  • ¥20 Win 10 LTSC 1809版本如何无损提升到20H1版本
  • ¥50 win10 LTSC 虚拟键盘不弹出
  • ¥30 微信小程序请求失败,网页能正常带锁访问
  • ¥15 Matlab求解微分方程,如何用fish2d进行预优?