除零

PHP7之前, 被0除会导致一条 E_WARNING 并返回 false. 一个数字运算返回一个布尔值是没有意义的,PHP7会返回如下的float值之一.

+INF
-INF
NAN
var_dump(1/0);

Output for 4.3.0 - 5.6.30, hhvm-3.10.1

Warning: Division by zero in /in/jQtKL on line 3
bool(false)

Output for hhvm-3.11.1 - 3.18.1, 7.0.0 - 7.1.3

Warning: Division by zero in /in/jQtKL on line 3
float(INF)
var_dump(42/0);  // float(INF)  + E_WARNING 
var_dump(-42/0); // float(-INF) + E_WARNING 
var_dump(0/0);   // float(NAN)  + E_WARNING

当使用取模运算符 % 的时候, PHP7会抛出一个 DivisionByZeroError 异常,PHP7之前, 则抛出的是警告.

var_dump(42 % 0);

Output for 7.0.0 - 7.1.3

Fatal error: Uncaught DivisionByZeroError: Modulo by zero in /in/rVdR4:3
Stack trace:
#0 {main}
  thrown in /in/rVdR4 on line 3

Process exited with code 255.

Output for 5.6.0 - 5.6.30

Warning: Division by zero in /in/rVdR4 on line 3
bool(false)

PHP7

try {
    42 % 0; 
} catch (\DivisionByZeroError $e) {    
    echo $e->getMessage();  // Modulo by zero
}

results matching ""

    No results matching ""