dongzhou1865 2015-05-16 13:40
浏览 85
已采纳

PHP类常量似乎总是被解释为字符串

A class constant always seems to be interpreted as a string although it is defined as an integer. Why does PHP do this kind of type juggling and how do I prevent it?

See the following code:

class BitSet {
  const NONE = 0;
  const FOO = 1;
  const BAR = 2;
  const ALL = 3;

  public function __construct( $flags = self::NONE ) {
    if( $flags & self::ALL !== $flags )
      throw new \OutOfRangeException( '$flags = '.$flags.' is out of range' );
    $this->value = $flags;
  }

  protected $value = self::NONE;
}

$bs = new BitSet( BitSet::FOO );

The last line (the invocation of the constructor) throws the OutOfRangeException:

PHP Fatal error:  Uncaught exception 'OutOfRangeException' with message '$flags = 1 is out of range' in test-case.php:12
Stack trace:
#0 /srv/www/matthiasn/class-constant-debug.php(19): BitSet->__construct('1')
#1 {main}
thrown in /srv/www/matthiasn/class-constant-debug.php on line 12

As you can clearly see from backtrace entry #0 the constant BitSet::FOO is passed as a character not as an integer. Hence, the bit mask operation $flags & self::ALL !== $flags is not performed on integers but on the bitwise ASCII representation and therefore fails.

What the hell?! Is there any better way to get this right than to do an explicit (int)-cast everywhere?

  • 写回答

2条回答 默认 最新

  • douke7431 2015-05-16 13:54
    关注

    I am not exactly sure what you expect, but note that !== has a higher precedence than & so you are doing a bitwise AND between 1 and true.

    Do you perhaps mean:

    if( ($flags & self::ALL) !== $flags )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?