PHP,如何将除数除以零? [英] PHP, How to catch a division by zero?

查看:152
本文介绍了PHP,如何将除数除以零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的数学表达式,必须动态创建.例如,一旦我解析了某物",结果将是一个字符串,例如:"$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?

首先,我想澄清一下:该表达式是动态构建的,因此,如果分母为零,我不能仅仅求值.所以...关于马克·贝克(Mark Ba​​ker)的评论,让我举一个例子.我的解析器可以构建如下内容:

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 ) )"

解析器逐步构建字符串而无需担心vars的值...因此,在这种情况下,如果$foz == $bak实际上存在除以零的内容:$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\n";
?> 

但它不会打印任何内容.

But it does not print anything.

推荐答案

if ($baz == 0.0) {
    echo 'Divisor is 0';
} else {
    ...
}

除了使用eval之外(如果您在已评估的表达式中使用用户输入,这非常危险),为什么不使用诸如

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屋!

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