使用按位运算符解释此方法的操作

时间:2015-10-22 09:25:52

标签: php error-handling bitwise-operators

有人可以解释这种方法背后的按位逻辑吗?它需要一个PHP错误级别,如果它是致命的,则返回。我想知道到底发生了什么。

    public static function isLevelFatal($level)
    {
        $errors = E_ERROR;
        $errors |= E_PARSE;
        $errors |= E_CORE_ERROR;
        $errors |= E_CORE_WARNING;
        $errors |= E_COMPILE_ERROR;
        $errors |= E_COMPILE_WARNING;
        return ($level & $errors) > 0;
    }

2 个答案:

答案 0 :(得分:3)

$foo |= $bar只是$foo = $foo | $bar的简写;
顺便提一下,这可以与许多其他运营商合作,例如$foo += 42

所以代码相当于:

$errors = E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING;

所以它构建了所有致命错误的掩码,然后告诉你$level是否在该位掩码中。

答案 1 :(得分:1)

写这个:

$errors = E_ERROR;
$errors |= E_PARSE;
$errors |= E_CORE_ERROR;
$errors |= E_CORE_WARNING;
$errors |= E_COMPILE_ERROR;
$errors |= E_COMPILE_WARNING;

与写这个相同:

$errors = E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR;

或者,像这样写,所以位掩码是显而易见的:

<?php
$errors = E_ERROR;
echo str_pad(decbin($errors), 10, ' ', STR_PAD_LEFT) . "\n";
$errors |= E_PARSE;
echo str_pad(decbin($errors), 10, ' ', STR_PAD_LEFT) . "\n";
$errors |= E_CORE_ERROR;
echo str_pad(decbin($errors), 10, ' ', STR_PAD_LEFT) . "\n";
$errors |= E_CORE_WARNING;
echo str_pad(decbin($errors), 10, ' ', STR_PAD_LEFT) . "\n";
$errors |= E_COMPILE_ERROR;
echo str_pad(decbin($errors), 10, ' ', STR_PAD_LEFT) . "\n";
$errors |= E_COMPILE_WARNING;
echo str_pad(decbin($errors), 10, ' ', STR_PAD_LEFT) . "\n";

将产生此输出:

         1
       101
     10101
    110101
   1110101
  11110101

它只是一次创建一个位掩码。然后进行比较,比较传递的$level是否在11110101中,例如:

  11110101 # the mask
         1 # E_ERROR in this? yes
        10 # E_WARNING in this? no

即。意图完全相同:

public static function isLevelFatal($level)
{
    return in_array(
        $level, 
        [
            E_ERROR,
            E_PARSE,
            E_CORE_ERROR,
            E_CORE_WARNING,
            E_COMPILE_ERROR,
            E_COMPILE_WARNING
    );
}