我有一个包含方法的类,这些方法需要返回它们的结果状态(true|false),并返回一个状态消息(“它工作了/由于x无法工作...”)。
这是我尝试过的两种方法…
第一种方法:返回布尔值,并通过引用传递消息
函数示例:
呼叫示例:
方法二:返回一个结果对象
函数示例:
你可以想象一下Result类的定义是什么样子的,所以我就不举例了。
调用示例:
什么是最好的方法,为什么?
这是我尝试过的两种方法…
第一种方法:返回布尔值,并通过引用传递消息
函数示例:
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;
}
呼叫示例:
$message = '';
if ( do_something($arg1, $arg2, $message) ) {
echo "It succeeded because $message.";
} else {
echo "It failed because $message."
}
方法二:返回一个结果对象
函数示例:
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);
}
你可以想象一下Result类的定义是什么样子的,所以我就不举例了。
调用示例:
$message = '';
$DoSomething = do_something($arg1, $arg2, $message);
if ( $DoSomething->success ) {
echo "It succeeded because ". $DoSomething->message;
} else {
echo "It failed because ". $DoSomething->message;
}
什么是最好的方法,为什么?
list($success, $message) = do_something($arg1, $arg2)
进行解包,类似于 Python 的元组赋值。 - candu