php 如何抑制“被零除”错误并将整个应用程序的结果设置为空?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3731710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to suppress the "Division by zero" error and set the result to null for the whole application?
提问by Ethan
How to suppress the "Division by zero" error and set the result to null for the whole application? By saying "for the whole application", I mean it is not for a single expression. Instead, whenever a "Division by zero" error occurs, the result is set to null automatically and no error will be thrown.
如何抑制“被零除”错误并将整个应用程序的结果设置为空?说“对于整个应用程序”,我的意思是它不是针对单个表达式。相反,每当发生“被零除”错误时,结果会自动设置为 null,并且不会抛出任何错误。
回答by Igor
This should do the trick.
这应该可以解决问题。
$a = @(1/0);
if(false === $a) {
$a = null;
}
var_dump($a);
outputs
产出
NULL
See the refs here error controls.
请参阅此处的错误控制参考。
EDIT
编辑
function division($a, $b) {
$c = @(a/b);
if($b === 0) {
$c = null;
}
return $c;
}
In any place substitute 1/0
by the function call division(1,0)
.
在任何地方1/0
由函数调用替代division(1,0)
。
EDIT - Without third variable
编辑 - 没有第三个变量
function division($a, $b) {
if($b === 0)
return null;
return $a/$b;
}
回答by Mark Lalor
Simple as.. well abc*123-pi
简单如..abc*123-pi
$number = 23;
$div = 0;
//If it's not 0 then divide
if($div != 0)
$result = $number/$div;//is set to number divided by x
}
//if it is zero than set it to null
else{
$result = null;//is set to null
}
As a function
作为函数
function mydivide($divisior, $div){
if($div != 0)
$result = $divisor/$div;//is set to number divided by x
}
//if it is zero than set it to null
else{
$result = null;//is set to null
}
return $result;
}
Useit like this
像这样使用它
$number = mydivide(20,5)//equals four
I can't think of a way to set it whenever there's divisionbut I'd use the function and rename itto something like "d"so it's short!
我想不出在有除法时设置它的方法,但我会使用该函数并将其重命名为“d”之类的名称,因此它很短!
回答by Matthew
This is a horrible solution, but thankfully, you won't use it because the variable is set to false
instead of null
.
这是一个可怕的解决方案,但幸运的是,您不会使用它,因为变量设置为false
而不是null
.
function ignore_divide_by_zero($errno, $errstring)
{
return ($errstring == 'Division by zero');
}
set_error_handler('ignore_divide_by_zero', E_WARNING);
In your case, I'd create a function that does your division for you.
在您的情况下,我会创建一个函数来为您进行除法。
回答by ToMSp
What about using a ternary operator, like so:
使用三元运算符怎么样,像这样:
$a = $c ? $b/$c : null;