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?
return array($success, $message);as welllist($success, $message) = do_something($arg1, $arg2), similar to Python tuple assignment.