How to suppress the "Division by zero" error and set the result to null for the whole application?

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.


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

EDIT - Without third variable

function division($a, $b) {         
    if($b === 0)
      return null;

    return $a/$b;
}

Simple as.. well 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;
}

Use it like this

$number = mydivide(20,5)//equals four

I can't think of a way to set it whenever there's division but I'd use the function and rename it to something like "d" so it's short!


This is a horrible solution, but thankfully, you won't use it because the variable is set to false instead of 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.

链接地址: http://www.djcxy.com/p/11900.html

上一篇: PHP,如何通过零来捕获一个分区?

下一篇: 如何在整个应用程序中禁止“除零除”错误并将结果设置为空?