June 13, 2012
PHP Function error handling and returning when foreach loop goes on a variable
Question by user1179459
*problem/confusion on how to handle this type problem in the php object oriented coding *
I have customer class which i need to suspend services for customers, however when the customer has pending work types for a service, i need to return a false for the calling function to do the error handle (i cant do it here becos it could be a email,output, or html)
however i am confused how to handle this as if use following code it will return false only on the last condition on the foreach loop i guess, any idea on how to handle this in the coding point of view
/**
* return false on failier
* Customer suspend all services for this customer
*
*/
public function suspendServices(){
$pending=false;
foreach ($this->services() as $service) {
$pending = $service->hasPendingWorktypes();
if($pending === true) {
return false;
}
$service->state()->changeTo(8);
}//end of foreach services
}//end of function
Answer by Starx
Exceptions is perfect for this job. The business method calling for the services can then onwards handle the part efficiently for the correct outcome.
public function suspendServices(){
$pending=false;
foreach ($this->services() as $service) {
$pending = $service->hasPendingWorktypes();
if($pending === true) {
throw new PendingExcpetion(); //Throw the exception
}
$service->state()->changeTo(8);
}//end of foreach services
}