I have a class with methods that need to return their result status (true|false) and also return a status message ("It worked/did not work because of x...").
Here are the two approaches I've tried...
Approach # 1: Return boolean and pass message by reference
Example of function:
function do_something ($arg1, $arg2, &$message) {
... do stuff resulting success...
// Give an explanation for why it succeeded... reasons could be varied:
$message = 'It succeeded and here are your instructions for celebrating: ...';
$success = true;
... do stuff resulting in failure...
// Give an explanation for why it failed... reasons could be varied:
$message = 'it failed because of so and so...';
$success = false;
return $success;
}
Example of call:
$message = '';
if ( do_something($arg1, $arg2, $message) ) {
echo "It succeeded because $message.";
} else {
echo "It failed because $message."
}
Approach # 2: Return a Result object
Example of function:
function do_something ($arg1, $arg2) {
... do stuff...
// Give an explanation for why it succeeded... reasons could be varied:
$message = 'It succeeded and here are your instructions for celebrating: ...';
$success = true;
... do stuff...
// Give an explanation for why it failed... reasons could be varied:
$message = 'it failed because of so and so...';
$success = false;
return new Result($success, $message);
}
You can imagine what the class definition of Result would like like, so I'll spare the example.
Example of call:
$message = '';
$DoSomething = do_something($arg1, $arg2, $message);
if ( $DoSomething->success ) {
echo "It succeeded because ". $DoSomething->message;
} else {
echo "It failed because ". $DoSomething->message;
}
What is the best approach and why?
I would go with returning an associative array with two elements:
return array('result' => true, 'message' => 'The operation executed fine!')
or
return array('result' => false, 'message' => 'The operation failed because...')
This way client code would access the values this way:
$retval = do_something();
if($retval['result']){
//...
}
else{
echo 'Ooups: ', $retval['message'];
}
Or, if you need these result values throughout many modules of your code I would go with approach #2 "Return a Result object", because by using this approach the data is more encapsulated.
Personal opinion: I definitely wouldn't use references in PHP, I just don't feel them in this language.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With