PHP,如何捕捉除以零? [英] PHP, How to catch a division by zero?
问题描述
我有一个必须动态创建的大型数学表达式.例如,一旦我解析了something",结果将是一个字符串:"$foo+$bar/$baz";
.
I have a large mathematical expression that has to be created dynamically. For example, once I have parsed "something" the result will be a string like: "$foo+$bar/$baz";
.
所以,为了计算该表达式的结果,我使用了 eval
函数......像这样:
So, for calculating the result of that expression I'm using the eval
function... something like this:
eval("$result = $expresion;");
echo "The result is: $result";
这里的问题是,有时我会收到错误信息,说被零除了,但我不知道如何捕获该异常.我尝试过类似的事情:
The problem here is that sometimes I get errors that says there was a division by zero, and I don't know how to catch that Exception. I have tried things like:
eval("try{$result = $expresion;}catch(Exception $e){$result = 0;}");
echo "The result is: $result";
或者:
try{
eval("$result = $expresion;");
}
catch(Exception $e){
$result = 0;
}
echo "The result is: $result";
但它不起作用.那么,当除以零时,如何避免我的应用程序崩溃?
But it does not work. So, how can I avoid that my application crashes when there is a division by zero?
首先,我想澄清一些事情:表达式是动态构建的,所以我不能只评估分母是否为零.所以...关于马克贝克的评论,让我给你举个例子.我的解析器可以构建这样的东西:
First, I want to clarify something: the expression is built dynamically, so I can't just eval if the denominator is zero. So... with regards to the Mark Baker's comment, let me give you an example. My parser could build something like this:
"$foo + $bar * ( $baz / ( $foz - $bak ) )"
解析器逐步构建字符串而不用担心变量的值...所以在这种情况下,如果 $foz == $bak</code> 实际上被零除:
$baz/( 0 )
.
The parser build the string step by step without worrying about the value of the vars... so in this case if $foz == $bak
there's in fact a division by zero: $baz / ( 0 )
.
另一方面,正如皮特所建议的那样,我尝试了:
On the other hand as Pete suggested, I tried:
<?php
$a = 5;
$b = 0;
if(@eval(" try{ $res = $a/$b; } catch(Exception $e){}") === FALSE)
$res = 0;
echo "$res
";
?>
但它不打印任何东西.
推荐答案
if ($baz == 0.0) {
echo 'Divisor is 0';
} else {
...
}
与其使用 eval,如果您在 evalled 表达式中使用用户输入,这是非常危险的,为什么不使用适当的解析器,例如 PHPClasses 上的evalmath,并在除以零时引发干净的异常
Rather than use eval, which is highly dangerous if you're using user-input within the evalled expression, why not use a proper parser such as evalmath on PHPClasses, and which raises a clean exception on divide by zero
这篇关于PHP,如何捕捉除以零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!