在将用户输入保存到数据库之前检查用户输入通常是最佳做法,这样您就可以在输出时对其充满信心。
您也可以使用 try/catch 块:
try {
$date = new DateTime('2016-12-12');
$date->modify('+1 dayBLA');
echo $date->format('Y-m-d');
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
编辑:查看此内容后,如果传递给modify 的字符串无效(不是我最初设想的日期字符串),您的代码将抛出Warning 而不是异常。
您可能能够触发Warning 暂时被视为set_error_handler 的异常。
function warning_handler($errno, $errstr, $errfile, $errline, array $errcontext) {
throwErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler('warning_handler', E_WARNING);
try {
$date = new DateTime('2016-12-12');
$date->modify('+1 daybla');
echo $date->format('Y-m-d');
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
restore_error_handler();
但是,这开始看起来有点讨厌。比较调用 modify 方法之前和之后的日期以查看它们是否不同可能会更清晰(在您的代码中,而不是在您的日志中)。
$date = new DateTime('2016-12-12');
$origDate = clone $date; //I believe this will get you an independent object
$date->modify('+1 daybla');
if ($origDate == $date) {
echo "Bad value passed to modify, probably a warning in the logs :(";
}