如果特定函数无法执行,PHP函数返回布尔值

如果特定函数无法执行,PHP函数返回布尔值

问题描述:

I have a PHP function which requires 2 arguments . The function calculates the number of days between that given 2 dates(arguments are given in MM/DD/YYYY format) . When I am passing invalid type of arguments PHP throws me an error . So my question is ... Is there a function or something like that which will catch that error (So that already PHP will not throw me an error) so I will be able to use that in my "if()" statments to see weather the function has been successfully executed ?

我有一个需要2个参数的PHP函数。 该函数计算给定2个日期之间的天数(参数以MM / DD / YYYY格式给出)。 当我传递无效类型的参数时,PHP会抛出一个错误。 所以我的问题是...是否有一个函数或类似的东西会捕获该错误(所以PHP已经不会给我一个错误)所以我 能够在我的“if()”声明中使用它来查看功能已成功执行的天气吗? p> div>

You should write your code but you can try something like this:

function diffDates($date1 , $date2)
{
  if(!isValidDate($date1) || !isValidDate($date2))
    return false;

 //Do something

 return true;
}

//Check if $date is in format: mm/dd/yy
function isValidDate($date)
{
 $temp = explode("/" , $date);
 if(!is_array($temp))
   return false;
 return checkdate($temp[0] , $temp[1] , $temp[2]);
}

Validate your date arguments before you pass them to your function. So check if arguments are valid dates.

http://php.net/manual/en/function.checkdate.php

You could also use the DateTime object and wrap them in try/catch like @linuxeasy recommended. It recognizes all sorts of date formats and even has a handy "diff" method you can apply to two DT objects. http://us.php.net/manual/en/datetime.diff.php