# PHP function to check if something valid or return error message [closed]

I would like to make a function that checks if something is valid, but if it can't then I want to return an error message that will probably be used to to throw an exception.

public function isTodayWithinDateRange(\DateTime $start, \DateTime$end) {
$now = new \DateTime(); if($now >= $start &&$now <= $end) return true; if($now < $start) return 'Today is before the start date'; if($now > $end) return 'Today is later than the end date'; }  And would probably use within a foreach as a validation check such as... if(isTodayWithinDateRange($myStart, $myEnd) !== true) { throw new Exception(isTodayWithinDateRange($myStart, $myEnd)); }  Is this a good way to go about it? I thought about putting the exception within the function, but this doesn't seem right as all that function should be doing is doing a check and the thing calling it should decide if an error is exceptional or not. I also thought about returning an array such as...  return array( 'success' => false, 'error' => 'Today is later than the end date' );  But I would expect isTodayWithinDateRange to return true if the answer is 'yes'. ## 1 Answer Simply , the method isTodayWithinDateRange can throw the exception in this case since the responsability of the method is to check the constraint . So , i think that you can try it as : function isTodayWithinDateRange(\DateTime$start, \DateTime $end) {$now = new \DateTime();
if($now <$start) throw new Excception('Today is before the start date') ;
if($now >$end) throw new Exception('Today is later than the end date');
return true;

}


First , start with case where you are looking to throw exception , in this case , it's not clearly , but think about a case where you have a lot of logic , here you should start with cases where you don't need to manipulate your logic (like if the argument is null , or missing ...) .

Call you method as :

$myStart = new Datetime('01-06-2012');$myEnd = new Datetime('01-06-2020');

// loop

try{

if(isTodayWithinDateRange($myStart,$myEnd)) {
echo 'contraint validated';

}
}catch(Exception $e){ echo$e->getMessage();
}
//end loop


• This is what I would have answered, but isTodayWithinDateRange() does not need to return true nor does it need to be inside a if (...) because it will only return when today is in the date range. I would also change the name to validateTodayIsWithinDateRange(), or something similar. Aug 1, 2019 at 17:24
• @dfhwze But do you ever see something like if (s.add("Welcome")) { ... } in Java? What if an else block is added to that if (...)? It won't ever work. Aug 1, 2019 at 17:50