为什么未定义的常量求值为true? [英] Why do undefined constants evaluate to true?

查看:107
本文介绍了为什么未定义的常量求值为true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

愚蠢的问题-我很惊讶这个咬了我。为什么PHP中未定义的常量求值为true?

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

测试用例:

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

上面的示例显示'Huh?'

The above example prints 'Huh?'

非常感谢您的帮助! :)

Thanks so much for your help! :)

推荐答案

尝试 defined('WHATEVER_THIS_ISNT_DEFINED')

当PHP遇到未定义的常量时,它将抛出 E_NOTICE ,并使用您尝试过的常量名称用作字符串。这就是为什么您的代码段打印 Hu !! 的原因,因为将评估一个非空字符串(不是 0 )到 true

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.

从手册中:


如果您使用未定义的常量,PHP
会假设您的意思是
常量本身的名称,就像您将
称为字符串一样(CONSTANT vs
常量)。当
发生时,将发出
E_NOTICE级错误。

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.

如果您设置了错误报告级别报告 E_NOTICE s(这是开发过程中的一个好习惯),您还会看到抛出的通知。

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.

  • PHP Constant Syntax
  • defined()
  • Casting to Boolean
  • error_reporting
  • error_reporting() function

这篇关于为什么未定义的常量求值为true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆