gpt4 book ai didi

PHP 函数/方法返回 bool 结果和状态消息

转载 作者:行者123 更新时间:2023-12-04 14:14:35 25 4
gpt4 key购买 nike

我有一个类,其方法需要返回其结果状态(true|false)并返回状态消息(“它工作/没有工作,因为 x ...”)。

这是我尝试过的两种方法...

方法#1:返回 bool 值并通过引用传递消息

函数示例:

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."
}

方法#2:返回一个结果对象

函数示例:
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;
}

什么是最好的方法,为什么?

最佳答案

我会返回一个包含两个元素的关联数组:

return array('result' => true, 'message' => 'The operation executed fine!')

或者
return array('result' => false, 'message' => 'The operation failed because...')

这样,客户端代码将以这种方式访问​​这些值:
$retval = do_something();
if($retval['result']){
//...
}
else{
echo 'Ooups: ', $retval['message'];
}

或者,如果您在代码的许多模块中都需要这些结果值,我会使用方法#2“返回结果对象”,因为通过使用这种方法,数据更加封装。

个人意见:
我绝对不会在 PHP 中使用引用,我只是在这种语言中感觉不到它们。

关于PHP 函数/方法返回 bool 结果和状态消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23414097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com